我想将数据通过管道传输到交互式命令中,并将交互式命令的输出作为另一个命令的输入接收。
例如,我希望能够执行以下操作:
echo "Zaphod" | hello.sh | goodbye.sh
并让输出为:
再见,你好,赞福德
这是我对此的初步破解,但我遗漏了一些东西;-) 我实际上希望 hello.sh 从列表中进行选择。
hello.sh
echo Please supply your name
read NAME
echo "HELLO $NAME"
再见.sh
MSG=$*
if [ -z "$1" ]
then
MSG=$(cat /dev/stdin)
fi
echo "BYE $MSG"
编辑:通过“从列表中选择”,我想我是在暗示我的真实用例,即从标准输出中获取任何内容,并让我选择一个选项,然后将其传递给其他内容的标准输入......例如:
ls /tmp | select_from_list | xargs cat
将允许我列出 /tmp/ 中的文件,以交互方式选择一个,然后 cat 该文件的内容。
所以我的“select_from_list”脚本实际上看起来像这样:
#!/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 https://stackoverflow.com/users/1944784/4ae1e1,我想出了如何做我想做的事 - 具体来说,如何获得我的select_from_list
日常工作:
所以现在我可以做这样的事情:
ls /tmp/ | select_from_list | xargs cat
从中选择一个文件/tmp
并猫它。
从列表中选择
#!/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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)