Occasionally I want to cd into a directory where my user does not have permission, so I resort to sudo.
The obvious command sudo cd somedir doesn't work:
$ 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
Using sudo su works:
$ sudo su
# cd test
Is it possible to make this into a one-liner? (Not a big deal, just idle curiosity :)
The variations I tried didn't work:
$ 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
The last one doesn't give an error, but it cd's within a new shell that exits by the end of the line, so it doesn't actually take me anywhere.
Can someone enlighten me as to why this happens? Why is sudo cd not found, when for example sudo ls ... works fine?
sudo -iis preferred oversudo su, otherwise the user's env vars will be carried over. – Sparhawk Apr 10 '14 at 04:54sudo -i). But then it should still be unnecessary to usesudo su, as there issudo -s. Running a root shell but not simulating an initial login shell is a common enough operation, and is considered reasonable enough, thatsudosupports it officially with the-soption. Note also that runningsudo -ifollowed bycd dir, whendiris a relative path that was originally correct, usually fails, as unlikesudo -s,sudo -ichanges the current directory to the target user's home directory. – Eliah Kagan Dec 11 '17 at 03:12