0

I want to make a simple bash script that makes a for loop over a file with commands and execute those commands, and finishes when an error happens. I have something like this

#!/bin/bash
while IFS= read -r line; do
    echo $line
    output=$(eval $line)
    if [ $? -eq 0 ]
    then
        echo ok
    else
        echo $output
        break
    fi
    echo
done < summary.txt

The problem is that the first command I'm trying to make is a sudo command, so I have to put the password. I tried putting it in the command like

sudo -S <<< password <<< Y command

with no luck. I've checked that works if I just put it directly without having to read it (not putting it as a string). The thing is that without the loop, the program would be long with no much sense.

Thanks

1 Answer 1

1
echo <password> | sudo -S < your command>

From man sudo

   -S, --stdin
                 Write the prompt to the standard error and read the password from the standard input instead of using the terminal
                 device.  The password must be followed by a newline character.

Sign up to request clarification or add additional context in comments.

5 Comments

There is one step missing. After the sudo I need to reply Y. In this case, when it's asked, it answers "abort"
Do you mean after running sudo command you want to get input from stdin ?
Yes. I need to install something (testing purposes) so I'm doing a sudo apt install. Normally it asks for password and to confirm Y/n, so I need to answer Y
How then about echo "<passwd>\nY" | sudo -S ..., or if you run into timing issues, (echo <passwd>; sleep 1; echo Y)|sudo -S ...?
(echo <passwd>; sleep 1; echo Y)|sudo -S .. solved my problem! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.