1

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?

pomsky
  • 68,507
cheesits456
  • 1,282
  • Which directory you want to cd into, normally on a stock Ubuntu system you should be able to cd everywhere except gvfs. Just do a sudo su in your terminal to become root, and exit will revert this change. – Videonauth Nov 20 '16 at 22:03
  • Trying to cd into another user's home folder – cheesits456 Nov 20 '16 at 22:04

2 Answers2

4

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.

cheesits456
  • 1,282
0

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"
jlliagre
  • 5,833