Tuesday, November 20, 2007

sudo hacks: making cd and redirection work

Suppose you want to run a command that requires root privileges. Conventional wisdom says don't login as root. Instead, login as a non-root user, and then sudo.
$ sudo 'cd /root/restricted'
sudo: cd /root/restricted: command not found

cd Not Found ?? That is RIGHT !

cd is a shell built-in command. It cannot be run in a child process. The child process simply cannot change the working directory of its parent shell process.

Redirection also does not work with sudo for the same reason (redirection being a shell "thing")
$ sudo 'ls /root/restricted >/root/out.txt'
sudo: ls /root/restricted >/root/out.txt: command not found

The workaround in both cases is to execute the command in a subshell.

$ sudo sh -c 'cd /root/restricted'

$ sudo sh -c 'ls /root/restricted >/root/out.txt'


Anonymous said...

Thanks for that. Worked a treat.

Anonymous said...

very nice, you could also just do "sudo su" and cd like normal

Anonymous said...

a better option than sudo su is sudo -i (or sudo -s depending on what you want to do)

Ariksu said...

Thank you, it helped so much!