sudo: cd: command not found

If you try to use sudo to get to a directory (for instance if the user calling sudo don’t have permissions for that folder) then you will see an error message like this

user@server:~$ sudo cd /var/log/
sudo: cd: command not found

While I don’t know how to get sudo to work with cd I can offer some workarounds.
As far as I can tell the problem with sudo cd is that if it would have worked the user would be in a directory that he/she has no permissions to so nothing is gained and having a folder that the user don’t have permissions to as the working directory might cause problems in more way than one.

  • Use “sudo ls” and then continue with the next command as sudo without entering that folder; for instance
      sudo ls /var/log
    sudo cat /var/log/syslog
  • Open a shell using sudo:
     sudo -s

    this will give you a shell with su permissions

  • simulate initial login using sudo:
     sudo -i

    this will also give you su permissions but with the difference that it will be like logging in like root (home dir, profile, variables etc) [this would be equivalent of running “sudo su”]

  • Use sudo to start a new shell and do all you need to do in this shell
     sudo sh -c 'cd /var/spool/exim4/;ls'

    (don’t miss the single quotes in the command)

To give some more details on the difference between -i and -s here is a excerpt from the man pages

-i [command]
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. sudo attempts to change to that user’s home directory before running the shell. It also initializes the environment, leaving DISPLAY and TERM unchanged, setting HOME, SHELL, USER, LOGNAME, and PATH, as well as the contents of /etc/environment on Linux and AIX systems. All other environment variables are removed.
-s [command]
The -s (shell) option runs the shell specified by the SHELL environment variable if it is set or the shell as specified in passwd(5). If a command is specified, it is passed to the shell for execution. Otherwise, an interactive shell is executed.