You can change the user mid-script, but this requires feeding the input to the shell and may not be portable to old and eldritch flavors of sh
) and is probably a bad idea:
$ cat changemidscript
who am i
sudo -i
who am i
$ bash < changemidscript
jhqdoe tty?? Oct 5 14:21
root tty?? Oct 5 14:21
$
However! bash changemidscript
or ./changemidscript
will both not behave the same as the above, which again points to this being a bad idea, as only the feed-the-input-in-via-standard-input will allow the user change and then the subsequent commands as that new user. (Did I mention you probably want to use a different way? You should!)
strace
may help show why this method works; shells may take pains to read the input line by line, so will either read in one character increments (so they can stop reading when a \n
is found) or will read into a buffer and then back the file handle up to the beginning of the next line for each line, depending on where the \n
are found.
sudo -i
, not the shell originally executing the script. – Kusalananda Feb 28 '19 at 15:17