1

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

1
  • Your script stores the first line of the stdout from the curl command into the variable yn. Since this line likely does not contain Y or N, you get the invalid response. You can verify this by doing a curl -s https://<myurl>/test.sh | head -n 1| tee| bash -s?. Commented Nov 17, 2023 at 7:09

1 Answer 1

1

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).

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

Comments

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.