How to pipe data to interactive bash script and pipe output to another command?

☆樱花仙子☆ 提交于 2019-12-12 08:57:39

问题


I'd like to pipe data into an interactive command, and have the output of the interactive command be received as input to another command.

For example, I'd like to be able to do something like the following:

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

and have the output be:

BYE HELLO Zaphod

Here's my initial crack at this, but I'm missing something ;-) I'd actually like the hello.sh to select 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: By "select from a list of things", I guess i'm implying my real use case, which is taking anything from stdout, and letting me choose one option, and pass it on to the stdin of something else... For example:

ls /tmp | select_from_list | xargs cat

would allow me to list the files in /tmp/, interactively pick one, then cat the contents of the file.

So my "select_from_list" script actually 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

回答1:


Thanks to 4ae1e1, I figured out how to do what I want - specifically, how to get my select_from_list routine to work:

So now I can do something like this:

ls /tmp/ | select_from_list | xargs cat

to choose 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


来源:https://stackoverflow.com/questions/34226734/how-to-pipe-data-to-interactive-bash-script-and-pipe-output-to-another-command

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