問題描述
有時我想 cd
進入我的用戶沒有權限的目錄,所以我求助於 sudo
。
明顯的命令 sudo cd somedir
不起作用:
$ sudo mkdir test
$ sudo chmod go-rxw test
$ ls -l
drwx------ 2 root root [...snip...] test
$ cd test
-bash: cd: test: Permission denied
$ sudo cd test
sudo: cd: command not found
使用 sudo su
作品:
$ sudo su
# cd test
有沒有可能把它變成one-liner? (沒什麽大不了的,隻是好奇:)
我嘗試的變化不起作用:
$ sudo "cd test"
sudo: cd: command not found
$ sudo -i cd test
-bash: line 0: cd: test: No such file or directory
$ sudo -s cd test
最後一個沒有給出錯誤,但它 cd 在一個新的 shell 中,在行尾退出,所以它實際上並沒有帶我去任何地方。
有人能告訴我為什麽會這樣嗎?為什麽找不到 sudo cd
,例如 sudo ls ...
工作正常?
最佳方案
從理論上講,問題在於如果您沒有目錄的執行權限,您應該無法讀取目錄的內容。現在假設你可以做你想做的事:
user@desktop:/$ sudo cd restricted-dir
user@desktop:/restricted-dir$ ls
file1 file2
如您所見,您使用 sudo 權限進入了該目錄,然後,當 sudo 返回時,您再次成為用戶,並且您處於通常不應該出現的目錄中。
從技術上講,問題如下。
sudo cd restricted-dir
cd
是 shell 內置,而不是命令。
sudo cd -i restricted-dir
您可能在 /root 中,但它會遇到與下一個相同的問題。
sudo cd -s restricted-dir
您打開一個新的 root shell,cd 進入目錄,然後退出 root shell,並返回到您開始的地方。
總而言之,唯一的解決方案是打開一個根 shell 並在您位於該目錄時保持打開狀態。
次佳方案
sudo sh -c "cd restricted-dir; some-other-command"
IE。
sudo sh -c "cd /root/restricted-dir; ls -l"
關鍵是“sh -c”,我經常使用它在同一個 shell 上下文/進程中運行一係列命令。