I have written a script which should execute certain commands as another user and after execution is finished (success or failure) should logout immediately.
I have read that I can use
su to execute commands. So, I wrote a script like:
#!/usr/bin/env bash su - user2 -c "echo 'hurray' && exit"
It executes the
echo command but stays logged in as
user2 doesn't logout. I even tried using
logout instead of
exit but it stays logged in. I need to execute script as
user1 which invokes the
su command and executes as
user2 and then the control should return to
user1 after completion.
Alright, I was to able logout automatically but this time some commands are not being executed. For eg:
su user2 -c 'echo 1'
And, then it logs out on its own.
su user2 -c 'bash some-script.sh'
bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell
So, whenever I try to run some script via
su, it displays the above mentioned error. I've tried many commands with
-c option such as
whoami etc. All these commands produced the correct output. But any command which tries to execute a script, it fails with the error.
su user2 -c 'bash --version' # Works su user2 -c 'bash some-script.sh' # Doesn't work
I cannot figure out why this is happening. And, so is the reason I'm unable to fix this error.