Skip to content

Commit 48ddd2d

Browse files
Fix shell cd error when working dir has been deleted (#41244)
root cause: if current dir has been deleted, then pwd() will throw an IOError: pwd(): no such file or directory (ENOENT) --------- Co-authored-by: Ian Butterworth <i.r.butterworth@gmail.com>
1 parent 61c044c commit 48ddd2d

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

base/client.jl

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ function repl_cmd(cmd, out)
4141
if isempty(cmd.exec)
4242
throw(ArgumentError("no cmd to execute"))
4343
elseif cmd.exec[1] == "cd"
44-
new_oldpwd = pwd()
4544
if length(cmd.exec) > 2
4645
throw(ArgumentError("cd method only takes one argument"))
4746
elseif length(cmd.exec) == 2
@@ -52,11 +51,17 @@ function repl_cmd(cmd, out)
5251
end
5352
dir = ENV["OLDPWD"]
5453
end
55-
cd(dir)
5654
else
57-
cd()
55+
dir = homedir()
5856
end
59-
ENV["OLDPWD"] = new_oldpwd
57+
try
58+
ENV["OLDPWD"] = pwd()
59+
catch ex
60+
ex isa IOError || rethrow()
61+
# if current dir has been deleted, then pwd() will throw an IOError: pwd(): no such file or directory (ENOENT)
62+
delete!(ENV, "OLDPWD")
63+
end
64+
cd(dir)
6065
println(out, pwd())
6166
else
6267
@static if !Sys.iswindows()

test/file.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1908,6 +1908,26 @@ end
19081908
end
19091909
end
19101910

1911+
@testset "pwd tests" begin
1912+
mktempdir() do dir
1913+
cd(dir) do
1914+
withenv("OLDPWD" => nothing) do
1915+
io = IOBuffer()
1916+
Base.repl_cmd(@cmd("cd"), io)
1917+
Base.repl_cmd(@cmd("cd -"), io)
1918+
@test realpath(pwd()) == realpath(dir)
1919+
if !Sys.iswindows()
1920+
# Delete the working directory and check we can cd out of it
1921+
# Cannot delete the working directory on Windows
1922+
rm(dir)
1923+
@test_throws Base._UVError("pwd()", Base.UV_ENOENT) pwd()
1924+
Base.repl_cmd(@cmd("cd \\~"), io)
1925+
end
1926+
end
1927+
end
1928+
end
1929+
end
1930+
19111931
@testset "readdir tests" begin
19121932
(a, b) = sort(a) == sort(b)
19131933
mktempdir() do dir

0 commit comments

Comments
 (0)