The commands in a script execute one by one, independently. The Script itself as the parent of all commands in the script, is another independent process and the su command does not and can not change it to root: the su command creates a new process with root privileges.
After that su command completes, the parent process, still running as the same user, will execute the rest of the script.
What you want to do is write a wrapper script. The privileged commands goes into the main script, for example ~/main.sh
#!/bin/sh
ls /root
The wrapper script calls the main script with root permissions, like this
#!/bin/sh
su -c ~/main.sh root
To launch this process you run the wrapper, which in turn launches the main script after switching user to the root user.
This wrapper technique can be used to turn the script into a wrapper around itself. Basically check to see if it is running as root, if not, use "su" to re-launch itself.
$0 is a handy way of making a script refer to itself, and the whoami command can tell us who we are (are we root?)
So the main script with built-in wrapper becomes
#!/bin/sh
[ `whoami` = root ] || exec su -c $0 root
ls /root
Note the use of exec. It means "replace this program by", which effectively ends its execution and starts the new program, launched by su, with root, to run from the top. The replacement instance is "root" so it doesn't execute the right side of the ||
sudo su
makes my eyes hurt.sudo -s
, though?sudo su
because I am more used to the options ofsu
than I am of those ofsudo
. I know the options of sudo well enough, but I can type the su ones faster. But yes I guess that means I don't know sudo well enough.sudo -i
is akin tosu -
whilesudo -s
operates likesu
(without the dash)