bash built-in command “select” not work via pipe in shell script

瘦欲@ 提交于 2020-04-21 08:11:22

问题


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.

For example, code snippet shows

#!/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

Directly using bash script.sh, works well.

$ bash /tmp/test.sh 
1) Red Hat
2) SUSE
3) Debian
Choose distribution:1
Result is Red Hat

Using pipe |, it will output

$ 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:

This makes the script not work.

I don't know why? Does select do not suppoer pipe | or anything else?


回答1:


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


来源:https://stackoverflow.com/questions/46402174/bash-built-in-command-select-not-work-via-pipe-in-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!