How can I cd into a directory as root?
Solution 1
Nope, there isn't a way to cd
to a directory that only allows root without being root. There really shouldn't be too many directories that have this limitation. Most of the time it's the access to a given file that's limited such as the /etc/shadow
file or specific log files under /var/log
.
You can use sudo ls <dir>
to see them instead of bash
. Also when using sudo
to become root you typically want to set user (su
command) instead of bash
, so use this command instead:
$ sudo su -
You can also accomplish the same thing with a sudo's -i
switch:
$ sudo -i
excerpt from man page regarding sudo -i
The -i (simulate initial login) option runs the shell specified in the passwd(5) entry of the target user as a login shell. This means that login-specific resource files such as .profile or .login will be read by the shell. If a command is specified, it is passed to the shell for execution. Otherwise, an interactive shell is executed.
For the files that you can't access you can use either of these sudo
commands:
$ sudo tail /var/log/messages
$ sudo less /etc/shadow
Solution 2
No, there isn't. You need a shell running as root.
Solution 3
Right, you can't. Here's a workaround though:
sudo sh -c "cd restricted-dir; some_command"
Related videos on Youtube
user2914606
Updated on September 18, 2022Comments
-
user2914606 over 1 year
Let's say there's a directory that I don't have the privileges to access. Obviously
sudo cd foo
won't work, becausecd
is a shell builtin in every shell ever.So far, I've just been using
sudo bash
(yes I know there are better ways) to get a root prompt. Then, I cancd
into the directory to poke around.Is there a better way to do this?
-
Stéphane Chazelas almost 11 yearsWhy would you use
sudo su -
instead ofsudo -i
? They both give you all superuser privileges though all you need is the CAP_DAC_READ_SEARCH capability. -
slm almost 11 years@StephaneChazelas - I've never noticed that switch before. My original introduction to
sudo
was through Solaris environments and the version ofsudo
that was there did not include this switch. Looking through the sudo changelog it looks like that option was added in 2004. Guess I'm dating myself with this but you asked 8-). I'll amend the answer to include both, thanks! -
tripleee almost 11 yearsAnd, as pointed out in comments, it's fairly pointless to
cd
unless you are running a shell or a comparable process. -
doug65536 over 8 years@StéphaneChazelas I agree. I prefer
sudo -Hi
because it sets the home directory too (it doesn't set home by default on my distro, the default can vary). If you don't, you may end up with root owned files in your home, if it creates new files there.