I have a shell script in which most of the commands need to be run under sesu
user and then I need to run some commands as current user. Can you please help me in this?
4 Answers
If you do not want to specify password every time, add sesu
to sudoers
group and run command you want this way:
sudo su -c "command string"
This way command string
runs as superuser (root etc).
-
Modify the sudoers file. In some operating systems, a "sudoers" group pre-exists and has some rights. You can authorize users to only run certain commands. An entirely different approach may be to use an SSH key which runs only specific commands. Those approaches can be combined. (Then also use MariusMatutiae's answer as necessary.)– TOOGAMMar 3, 2016 at 0:46
The command
exit
closes the current shell. If you were running a shell like user X, then switched to a user Y, exit closes the shell in which you were Y and returns you to being X
I have been in a similar situation recently. Here is what I have done to go to superuser level immediately when a script is called, and subsequently perform regular-user tasks. I think it may help you figure a way to get to the desired solution:
#!/bin/bash
# generic_sudo.sh
# Tool that demonstrates in-then-out of sudo
# This demo is pointless if called with 'sudo generic_sudo.sh'
# Need root priviledges for some superuser work
if (( EUID != 0 )); then # If the user is not "root":
# In general one should use ((..)) for testing numbers and integer variables, and [[..]] for testing strings and files.
sudo $0 # Relaunch it as "root".
EXITCODE=$?
printf "su mode OFF.\n" # If we got here, we left superuser mode
printf "EUID is: %d\n" $EUID
printf "Exit code %d\n" $EXITCODE
exit $EXITCODE # Once it finishes, exit gracefully.
else
printf "su mode ON.\n"
fi # End if.
printf "EUID is: %d\n" $EUID
# Some superuser work
printf "Some superuser work was done.\n"
exit 0