Skip to content
Joachim Ansorg edited this page Nov 12, 2021 · 2 revisions

Can't use sudo with builtins like cd. Did you want sudo sh -c .. instead?

Problematic code:

sudo cd /root
pwd

Correct code:

sudo sh -c 'cd /root && pwd'

Rationale:

Due to the Unix process model, sudo can only change the privileges of a new, external process. It can not grant privileges to a currently running process.

This means that shell builtins -- commands that are interpreted by the current shell rather than through program invocation -- cannot be run with sudo. This includes cd, source, read, and others.

Instead you can run a shell with sudo, and have that shell run the builtins you want. Just be aware that what happens in that shell stays in that shell:

sudo sh -c 'cd /root && pwd'  # This shows /root
pwd                           # This shows the original directory

Exceptions:

None.

Related resources:

  • SuperUser: Why won't “sudo cd” work?
  • Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally