bash内置命令"select"在shell脚本中无法通过管道工作 [英] bash built-in command "select" not work via pipe in shell script
本文介绍了bash内置命令"select"在shell脚本中无法通过管道工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用bash内置命令 select
编写了一个Shell脚本,以创建选择菜单.直接通过 bash
调用时,它的效果很好.但是,如果使用管道|
(例如cat script.sh | bash
),则 select 函数将无法正常工作.
I wrote a shell script using bash built-in command select
to create selection menu. It works well when invoking by bash
directly. But if I use pipe |
such as cat script.sh | bash
, the select function will not work.
例如,显示代码段
#!/usr/bin/env bash
arr=("Red Hat" "SUSE" "Debian")
PS3="Choose distribution:"
result=${result:-}
select item in "${arr[@]}"; do
result="${item}"
[[ -n "${result}" ]] && break
done
echo "Result is ${result}"
unset PS3
直接使用bash script.sh
效果很好.
$ bash /tmp/test.sh
1) Red Hat
2) SUSE
3) Debian
Choose distribution:1
Result is Red Hat
使用管道|
,它将输出
$ cat /tmp/test.sh | bash
1) Red Hat
2) SUSE
3) Debian
Choose distribution:1) Red Hat
2) SUSE
3) Debian
Choose distribution:Choose distribution:Choose distribution:
这使脚本不起作用.
我不知道为什么? select
是否不支持管道|
或其他任何内容?
I don't know why? Does select
do not suppoer pipe |
or anything else?
推荐答案
select
从标准输入中读取. stdin
来自管道.如果要从tty中获取数据,可以尝试:
select
reads from stdin. stdin
is coming from the pipe. If you want to get data from the tty, you can try:
#!/usr/bin/env bash
arr=("Red Hat" "SUSE" "Debian")
PS3="Choose distribution:"
result=${result:-}
select item in "${arr[@]}"; do
result="${item}"
[[ -n "${result}" ]] && break
done < /dev/tty # <------------------
echo "Result is ${result}"
unset PS3
这篇关于bash内置命令"select"在shell脚本中无法通过管道工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文