简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM