简体   繁体   中英

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

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 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM