Search code examples
bashsudo

How to pass password to sudo from environment variable without prompt appearing?


How do I pass my password to sudo from an environment variable through stdin without the sudo prompt appearing?

I have tried $ echo $PASSWORD | sudo -S echo foo but that returns [sudo] password for mithic: foo. Using the -n flag just always returns sudo: a password is required (unless I have recently inputted the correct password).


Solution

  • If it's really in the environment, I would recommend using the -A option instead of -S. Write a very small script that writes the value to standard output.

    #!/bin/sh
    
    printf '%s' "$PASSWORD"
    

    Call it something like asker and make it executable

    chmod +x asker
    

    The do the following:

    SUDO_ASKPASS=./asker sudo -A echo foo
    

    -A makes sudo run the executable named by SUDO_ASKPASS and read the password from its output.