简体   繁体   English

如何从管道传输到 bash 的脚本中读取用户输入

[英]How to read user input from a script piped to bash

I want to read user input from inside a bash script test.sh :我想从 bash 脚本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.当使用./test.shbash test.sh直接运行脚本时,效果很好。

However, I want to run this script (well, a more complicated version of it) from a URL so am calling it like this:但是,我想从一个 URL 运行这个脚本(好吧,它的一个更复杂的版本)所以我这样称呼它:

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).这会运行脚本,但它只显示Invalid Response ,没有别的(甚至不打印“你想继续吗?”消息)。 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?我知道这是因为来自 curl 的标准输出通过管道传输到 bash 的标准输入,但在这种情况下如何读取用户输入?

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).以防止从stdin (您的管道) read

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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