I want to cd into a directory from the terminal but access is denied, and typing sudo cd (directory) returns an error about sudo not supporting the cd command. I can use sudo gnome-terminal to launch a new terminal window with root privileges, but I want a solution that I can use from the same non-root terminal window. Is there a way to make the cd command compatible with sudo?
- 70,557
- 1,354
2 Answers
I'm afraid it's not possible to use cd with sudo directly. sudo can call executables, for example sudo ls, but cd is a builtin command of the shell. In other words, there's a file that contains the executable script for ls (/bin/ls), but there's no file for cd, so you can't use cd with sudo.
- 1,354
- 8,502
Well, you certainly can run the following command:
sudo sh -c "cd somedirectory"
and technically, you'll have changed the current directory of the launched subshell. The issue is that subshell will exit immediately and your main shell wouldn't have its own directory changed.
The main issue is that if you can't cd to a directory, you can't run either a shell inside it with your current account.
A workaround is to switch to a user account that has this right, and root is of course the simplest choice:
sudo sh -c "cd somedirectory; sh"
- 5,983