Let’s say there’s a directory that I don’t have the privileges to access. Obviously sudo cd foo won’t work, because cd 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 can cd into the directory to poke around.
Is there a better way to do this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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
Method 2
No, there isn’t. You need a shell running as root.
Method 3
Right, you can’t. Here’s a workaround though:
sudo sh -c "cd restricted-dir; some_command"
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0