如何通过管道将数据传输到交互式bash脚本并将管道输出到另一个命令? [英] How to pipe data to interactive bash script and pipe output to another command?
问题描述
我想将数据传递到交互式命令中,并让交互式命令的输出作为另一个命令的输入被接收.
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
的输出为:
BYE HELLO Zaphod
BYE HELLO Zaphod
这是我的初衷,但是我错过了一些东西;-)我实际上希望hello.sh从事物列表中进行选择.
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"
通过从事物列表中选择",我想我的意思是我的实际用例是从stdout中获取任何内容,然后让我选择一个选项,并将其传递给其他内容的stdin....例如:
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
请允许我在/tmp/中列出文件,以交互方式选择其中一个,然后整理文件内容.
would allow me to list the files in /tmp/, interactively pick one, then cat the contents of the file.
所以我的"select_from_list"脚本实际上看起来像这样:
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
推荐答案
感谢 4ae1e1 ,我想出了如何做我想做的-具体来说,如何使我的 select_from_list
例程正常工作:
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
从/tmp
中选择一个文件并将其分类.
to choose a file from /tmp
and cat it.
#!/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
这篇关于如何通过管道将数据传输到交互式bash脚本并将管道输出到另一个命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!