From 405fb7eb86c0d1f2094bf0b36a9d732e3399e7ac Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Mon, 30 Apr 2018 22:58:48 -0700 Subject: [PATCH] Created SC2232 (markdown) --- SC2232.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 SC2232.md diff --git a/SC2232.md b/SC2232.md new file mode 100644 index 0000000..636032f --- /dev/null +++ b/SC2232.md @@ -0,0 +1,33 @@ +## Can't use sudo with builtins like cd. Did you want sudo sh -c .. instead? + +### Problematic code: + +```sh +sudo cd /root +pwd +``` + +### Correct code: + +```sh +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](https://superuser.com/questions/241129/why-wont-sudo-cd-work): Why won't “sudo cd” work? +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file