Error: su: must be run from a terminal

17,258

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"
Share:
17,258
Divya Singh
Author by

Divya Singh

Updated on September 18, 2022

Comments

  • Divya Singh
    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 with sudo. 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
      binarysta almost 4 years
      Does this answer your question? login to root user with password inside script only
    • Divya Singh
      Divya Singh almost 4 years
      No. 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
      terdon over 3 years
      Why are you using -s? What are you trying to achieve with this command? Aren't you getting an su: option requires an argument -- 's' error?
  • annahri
    annahri almost 4 years
    Please elaborate
  • AdminBee
    AdminBee almost 3 years
    Welcome 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.