Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read user input from a script piped to bash

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading