"sudo cd ..." one-liner? [duplicate]

Theoretically, the problem is that if you don't have execute rights to a directory, you shouldn't be able to read the contents of the directory. Now suppose you could do what you wanted:

user@desktop:/$ sudo cd restricted-dir
user@desktop:/restricted-dir$ ls
file1 file2

As you can see, you entered the directory using sudo privileges, then, when sudo returns, you become a user again, and you are in a directory where you normally shouldn't be.

Technically, the problem is the following.

sudo cd restricted-dir

cd is a shell built-in, not a command.

sudo cd -i restricted-dir

You are probably in /root, but it would have the same problem as with the next one.

sudo cd -s restricted-dir

You open a new root shell, cd into the directory, then exit the root shell, and return to where you began.

All in all, the only solution is to open a root shell and keep it open while you are in that directory.


sudo sh -c "cd restricted-dir; some-other-command"

i.e.

sudo sh -c "cd /root/restricted-dir; ls -l"

the key piece is "sh -c" which I use quite often to run a chain of commands in the same shell context/process.