2015-07-22 56 views
1

在bash中调用函数时是否可以提示用户输入?用户输入提示功能/管道如果声明 - Bash

借此例如:

#!/bin/bash 
test1(){ 

echo "Do you wish to install this program?" 
select yn in "Yes" "No"; do 
    case $yn in 
     Yes) make install; break;; 
     No) exit;; 
    esac 
done 

} 

pip list 2>/dev/null | if grep httplib2; then echo 2>/dev/null; else test1; fi 

无视我检查httplib2的,因为我知道,如果你到别的回声“测试”工作正常的事实。我已经用stackoverflow和tldp的例子试过了,所以我现在有点困惑。

你不能从管道if语句中捕获用户输入吗?

pip list 2>/dev/null | if grep httplib2; then 
echo 2>/dev/null; 
else 
echo "Type the year that you want to check (4 digits), followed by [ENTER]:" 
read year 
echo $year 
fi 

只是测试,以及与有同样的效果。

回答

1

如果test1是管道,但你需要从终端输入,使用方法:

test1 </dev/tty 

例如:

pip list 2>/dev/null | if grep httplib2; then echo 2>/dev/null; else test1 </dev/tty; fi 

test1从标准输入获取输入。如果你想与它交互,它的标准输入必须来自终端,而不是来自管道的/dev/tty

另一种方法是在管道启动之前捕获stdin的句柄。例如:

exec 3<&0; echo http | test1 <&3; exec 3<&- 

或者,

exec 3<&0 
pip list 2>/dev/null | if grep httplib2; then echo 2>/dev/null; else test1 <&3; fi 
exec 3<&- 
+0

如果我用'EXEC 3 <&0;回声http | test1 <&3'我得到一个破损的管道。 – 123

+0

我认为“if grep”从stdout获得了输入,然后声明的其余部分就是它是真是假? – Chirality

+0

@Revolt起初似乎是合理的,但if-then-else结构是一个_compound command_。如果复合命令的stdin被重定向,那么,除非我们明确地改变它,复合命令中的每个语句都会看到重定向的stdin。 – John1024