Quote:
Originally Posted by sonichedgehog
It's also made me think about the use of sh -c with && - I'm assuming that && is is used either within a script or a alias and therefore requires sh -c?
|
In POSIX and Bourne shells,
&& is an operator that can be read as "
and if successful, then".
The idea behind
Code:
sudo sh -c 'cd /some/directory && some-command ...'
is that the entire sh scriptlet (the part in single quotes) is run as root, and that
some-command ... is run only if the
cd command succeeds. If
/some/directory cannot be entered,
some-command ... will not be run.
Because current working directory is a per-process concept, using
Code:
cd /some/directory && sudo some-command ...
is not the same thing; it changes the working directory in the original shell first. After the command is run, the working directory has changed to /some/directory in the original shell.
Using the
sudo sh -c 'cd ... && command' construct, the working directory is only changed in the subshell running as root, not in the original shell. During and after the command is run, the working directory for the original shell does not change at all.
(Using
sudo cd /some/directory && some-command ... would change the directory as root in a sub-shell, but the sub-shell would immediately exit. The
some-command ... would be run in the original shell, and not with root rights.)
In other words, because I have a command or commands I'd like to run, as root, using a POSIX or Bourne shell, I use
sudo sh . The
-c '...' is actually a parameter to
sh, specifying the commands it should run.