Home > database >  How to read user input from a script piped to bash
How to read user input from a script piped to bash

Time:12-17

I want to read user input from inside a bash script test.sh:

#!/bin/bash
read -p "Do you want to continue? (y/n) " yn

case $yn in 
    [yY] ) echo "Doing stuff...";
        echo "Done!";;
    [nN] ) echo "Exiting...";
        exit;;
    * ) echo "Invalid response";;
esac

When running the script directly using either ./test.sh or bash test.sh this works fine.

However, I want to run this script (well, a more complicated version of it) from a URL so am calling it like this:

curl -s https://<myurl>/test.sh | bash -s

This runs the script but it only displays Invalid Response, nothing else (doesnt even print the "Do you want to continue?" message). I understand that this is because the stdout from curl is piped to stdin for bash but how is it possible to read user input in this case?

For completeness, I also get the same behaviour if the script is saved locally and I do:

bash < test.sh

CodePudding user response:

I suggest to replace

read -p "Do you want to continue? (y/n) " yn

with

read -p "Do you want to continue? (y/n) " yn </dev/tty

to prevent read from reading from stdin (your pipe).

  • Related