这个bash脚本为什么不从stdin读取,而是终止了?

huangapple go评论57阅读模式
英文:

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语句之后)仍然会打印出来。似乎stdinselect没有连接,我怀疑这可能与我从管道中读取选项的方式有关(如果我错了,请纠正我)。

我该如何更改/修复代码以使其像这样工作?

$> 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 &quot;${arr[@]}&quot;; do
    echo $sel;
    break;
  done &lt;/dev/tty

huangapple
  • 本文由 发表于 2023年2月27日 15:27:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定