Equivalent of AppleScript "with administrator privileges" in shell
sudo
is the command-line equivalent of AppleScript's with administrator privileges
. That is, when you run sudo somecommand
, then somecommand
will run as root. Here's a quick demo:
$ sudo whoami
Password: [I entered my password here]
root
One thing you have to be aware of, though, is that sudo
only runs the actual command as root, not things like redirections. So if you use something like this:
sudo somecommand <inputfile >outputfile
...opening inputfile
and outputfile
will be done by your current shell, as the current user, before sudo
and the command run. There are standard ways to get around this, like running a root shell to do the redirections and run the command:
sudo sh -c 'somecommand <inputfile >outputfile'
(Warning: if the command you want to run contains single-quotes and/or any shell variables, things are more complicated.) Another standard trick is to use sudo cat
to read files as root and/or sudo tee
to write files as root:
sudo cat inputfile | somecommand | sudo tee outputfile >/dev/null
(Note that in this example, cat
and tee
are run as root, but somecommand
runs as your normal user.)
You can also use sudo -s
to open an interactive root shell, and then run a bunch of commands as root (and then use exit
to close that shell and go back to normal). But be careful when running as root; it's fairly easy to make a complete mess if you don't know exactly what you're doing.