Rob*_*low 10 shell bash pipe read
我需要通过bash使用管道来运行脚本wget(而不是直接使用 bash 运行它)。
$ wget -O - http://example.com/my-script.sh | bash
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为我的脚本中有read语句。出于某种原因,这些在管道到 bash 时不起作用:
# Piping to bash works in general
$ echo 'hi'
hi
$ echo "echo 'hi'" | bash
hi
# `read` works directly
$ read -p "input: " var
input: <prompt>
# But not when piping - returns immediately
$ echo 'read -p "input: " var' | bash
$
Run Code Online (Sandbox Code Playgroud)
取而代之的提示input:和要求的值,因为它应该读命令只是获取由经过bash。
有谁知道我如何用readto管道脚本bash?
Gil*_*il' 17
read从标准输入读取。但是 bash 进程的标准输入已经被脚本采用了。取决于外壳,要么read不会读取任何内容,因为外壳已经读取并解析了整个脚本,要么read会消耗脚本中不可预测的行。
简单的解决方案:
bash -c "$(wget -O - http://example.com/my-script.sh)"
Run Code Online (Sandbox Code Playgroud)
更复杂的解决方案,更多的是用于教育目的,而不是为这个特定场景说明一个好的解决方案:
echo '{ exec </dev/tty; wget -O - http://example.com/my-script.sh; }' | bash
Run Code Online (Sandbox Code Playgroud)