英文:
Why doesn't this bash script read from stdin but rather terminates?
问题
我正在编写一个非常简单的zsh-select的替代品,用于在我的bash脚本中使用。这是我的.bashrc的一部分。
bash-select(){
declare -a arr;
while read l; do
arr+=( "$l" );
done
PS3="$1: ";
if [[ -z "$1" ]]; then PS3="Choose: "; fi
select sel in "${arr[@]}"; do
echo $sel;
break;
done
}
然而,运行它时,select不会查询stdin以获取值,而会立即以退出码1终止。尽管如此,脚本末尾的echo语句(在select语句之后)仍然会打印出来。似乎stdin与select没有连接,我怀疑这可能与我从管道中读取选项的方式有关(如果我错了,请纠正我)。
我该如何更改/修复代码以使其像这样工作?
$> ls | bash-select
1) file1
2) file2
3) file3
Choose: 3
file3
英文:
I am writing a very simple drop-in replacement for zsh-select to use in my bash scripts. This is part of my .bashrc
bash-select(){
declare -a arr;
while read l; do
arr+=( "$l" );
done
PS3="$1: ";
if [[ -z "$1" ]]; then PS3="Choose: "; fi
select sel in "${arr[@]}"; do
echo $sel;
break;
done
}
Running it, however, select does not query stdin for a value but instantly terminates with exit code 1.
echos at the end of the script (after the select statement) get printed nevertheless.
It seems as if stdin is not connected to select and I suspect it might be the way in which i read the options from the pipe. (Please correct me, if this is wrong.)
How could I change/fix the code to make it work like this?
$> ls | bash-select
1) file1
2) file2
3) file3
Choose: 3
file3
答案1
得分: 1
select 不会查询标准输入以获取值,而是立即以退出码 1 终止。
它确实会查询标准输入,但由于您的 while 循环消耗了所有输入,所以会得到 EOF。尝试将其输入重定向到终端:
select sel in "${arr[@]}"; do
echo $sel;
break;
done </dev/tty
英文:
>select does not query stdin for a value but instantly terminates with exit code 1
It does query stdin but gets EOF because your while loop consumes all input. Try redirecting its input from the terminal:
select sel in "${arr[@]}"; do
echo $sel;
break;
done </dev/tty
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论