Error: su: must be run from a terminal
Quite likely something down to syntax/interactive shell from what I googled so far, but I am no expert!
Below works for me, even if technically su should not be used in a shell script, sudo is more secure.
This works:
#!/bin/bash
exec su root --command 'echo -e "hello world" >> "/home/parallels/rootWasHere.txt"'
And so does this:
#!/bin/bash
runAsRoot="
printf \"\nhey there\n\"
printf \"\nhello world, I am root\n\" >> \"/home/parallels/rootWasHere.txt\"
"
exec su root -c "$runAsRoot"
Also, in regards to -s option for su, that specifies only the shell according to the manual. This doesn't imply that it will also execute what's passed afterwards/ to -s, so I think you could something on the lines of:
#!/bin/bash
runAsRoot="
printf \"\nhey there\n\"
printf \"\nhello world, I am root and my shell is \$SHELL\n\" >> \"/home/parallels/rootWasHere.txt\"
"
exec su root -s /bin/zsh -c "$runAsRoot"
Divya Singh
Updated on September 18, 2022Comments
-
Divya Singh over 1 year
When I try to login to root user using shell script given below, it throws an error:
su: must be run from a terminal
The srcipt (
scriptfile.sh
) looks as follows:su -s <<EOF echo Now i am root whoami EOF
Although I can successfully do
su
from the terminal, it logs in to the root user by default.FYI: Same script is working fine when we replace
su
withsudo
. I am running this script as normal user, not as root.What can be the possible reason for the error and how can I solve this?
Note: I want to get it done without touching
/etc/sudoers
file.-
binarysta almost 4 yearsDoes this answer your question? login to root user with password inside script only
-
Divya Singh almost 4 yearsNo. Its a different question entirely. I didn't ask this question over there to avoid mixing up of two topics. If you look into the scripts carefully you will find a very big difference, one uses sudo and the the other uses su. With sudo its working fine, but with su its not. Question has been edited for more clarification
-
terdon over 3 yearsWhy are you using
-s
? What are you trying to achieve with this command? Aren't you getting ansu: option requires an argument -- 's'
error?
-
-
annahri almost 4 yearsPlease elaborate
-
AdminBee almost 3 yearsWelcome to the site, and thank you for your contribution. Please note that link-only answers are discouraged, as the link may become invalid or the linked content change. Please edit your answer to include at least a summary of the linked explanation.