user3356760 user3356760 - 1 year ago 214
Bash Question

shell script giving "sudo: no tty present and no askpass program specified" when trying to execute sudo command

  • I have a shell script which creates a user and executes another script as that user

    sudo useradd -m devops
    sudo passwd devops
    sudo adduser devops sudo
    su - devops -c "sh /path/to/"

  • This script creates the user,sets the password and adds user to sudo group as expected.

  • contains commands which uses sudo previlages. (sudo apt-get update, sudo apt-get install software-properties-common etc.). And other commands like ssh-keygen,curl and wget.

  • All commands except the one's with sudo are executed correctly and producing results as excepted.

  • But commands having sudo fails by giving the error "no tty present and no askpass program specified"

  • Why does this happen in this case and how can I overcome this?

  • I have seen similiar questions but will be thankful if I get a clear explanation in this context,thank you.

Answer Source

Try to replace this:

su - devops -c "sh /path/to/"

with this:

sudo -u devops -H sh -c "sh /path/to/"

The -c option of su doesn't support interactive mode:

-c, --command COMMAND Specify a command that will be invoked by the shell using its -c.

The executed command will have no controlling terminal. This option cannot be used to execute interractive programs which need a controlling TTY.

(man su)

By the way, I wouldn't use sudo within a script everywhere. The script might simply require root permissions. Within the script you might drop privileges where necessary by means of the above-mentioned sudo command.