Change user in script

i have a script that needs to be run as a specific user. lets call this specific user "skysmart".

sure, i can check the username of the person running the script and if it isn't "skysmart", simply abort with a descriptive error message. but then, that would require the user to have to "sudo su -" to skysmart and then rerun the script. i'd like to avoid this.

so, if this script is run as root, i want it to automatically "sudo su -" to "skysmart", and then run. without any further intervention from the user.

sample code:

if [ "${LOGNAME}" = "root" ] ; then

su - skysmart

........
.......
.......
.......

fi

That's not going to work. su interrupts the execution of the shell script until you log out of the "su session".

If you are logged in as root all the time, and are using the script as a shortcut to execute commands as skysmart, that's not a good idea. Instead, just stay logged in as skysmart. When you need to do something special (usually not that often), login as root, or use sudo.

The script can call itself:

if [ "${LOGNAME:-$USER}" = "root" ] ; then
 echo "rerunning $0 as user skysmart"
 sleep 1 # for safety
 su - skysmart -c "$0 $@" fi
# this is run as user skysmart
...

this could work. is this a typo:

[ "${LOGNAME:-$USER}" = "root" ] 

should it be:

[ "${LOGNAME}:-${USER}" = "root" ] 

No just a habit, to try $USER if $LOGNAME is not present.
There might be shells or conditions where LOGNAME is not set...

man sh
...
     ${parameter:-word}      If parameter is set and is non-null,
                             substitute its value; otherwise sub-
                             stitute word.
1 Like

like if you replace the "$0" with the actual path of to the script, it hangs.

If you call the script with a relative pathname,
it is safer to replace $0 by the abolute path to this script.
Then I forgot an exec .
Then the fi somehow went to the end of the previous line

if [ "${LOGNAME:-$USER}" = "root" ] ; then
 echo "rerunning $0 as user skysmart"
 sleep 1 # for safety
 exec su - skysmart -c "/path/to/this/script $@"
fi
# this is run as user skysmart
echo "hello I am $LOGNAME"
1 Like