How to connect data to an interactive bash script and output to another channel?

I would like to pass the data to an interactive command and get the output of the interactive command as input to another command.

For example, I would like to do something like the following:

echo "Zaphod" | hello.sh | goodbye.sh 

and have an exit:

BYE HELLO Zaphod

Here is my initial crack in this, but I'm missing something ;-) I would like hello.sh to choose from a list of things.

hello.sh

 echo Please supply your name read NAME echo "HELLO $NAME" 

goodbye.sh

 MSG=$* if [ -z "$1" ] then MSG=$(cat /dev/stdin) fi echo "BYE $MSG" 

EDIT: β€œFrom a list of things,” I suppose I mean my real use case, which takes something from stdout and allows me to select one option and pass it to stdin for something else ... For example:

ls /tmp | select_from_list | xargs cat

will allow me to list the files in / tmp /, interactively select one, and then cat the contents of the file.

So my "select_from_list" script looks like this:

 #!/bin/bash prompt="Please select an option:" options=( $* ) if [ -z "$1" ] then options=$(cat /dev/stdin) fi PS3="$prompt " select opt in "${options[@]}" "Quit" ; do if (( REPLY == 1 + ${#options[@]} )) ; then exit elif (( REPLY > 0 && REPLY <= ${#options[@]} )) ; then break else echo "Invalid option. Try another one." fi done echo $opt 
+3
bash zsh
Dec 11 '15 at 15:16
source share
1 answer

Thanks to 4ae1e1, I figured out how to do what I want - in particular, how to make my select_from_list subroutine work:

So now I can do something like this:

ls /tmp/ | select_from_list | xargs cat

to select a file from /tmp and cat it.

select_from_list

 #!/bin/bash prompt="Please select an item:" options=() if [ -z "$1" ] then # Get options from PIPE input=$(cat /dev/stdin) while read -r line; do options+=("$line") done <<< "$input" else # Get options from command line for var in "$@" do options+=("$var") done fi # Close stdin 0<&- # open /dev/tty as stdin exec 0</dev/tty PS3="$prompt " select opt in "${options[@]}" "Quit" ; do if (( REPLY == 1 + ${#options[@]} )) ; then exit elif (( REPLY > 0 && REPLY <= ${#options[@]} )) ; then break else echo "Invalid option. Try another one." fi done echo $opt 
+1
Dec 22 '15 at 13:15
source share



All Articles