如何将数据通过管道传输到交互式 bash 脚本并将输出通过管道传输到另一个命令?

Bra*_*rks 5 bash zsh

我想将数据通过管道传输到交互式命令中,并将交互式命令的输出作为另一个命令的输入接收。

例如,我希望能够执行以下操作:

echo "Zaphod" | hello.sh | goodbye.sh
Run Code Online (Sandbox Code Playgroud)

并有输出:

再见,赞福德

这是我对此的初步破解,但我错过了一些东西 ;-) 我实际上希望 hello.sh 从事物列表中进行选择。

你好.sh

echo Please supply your name
read NAME
echo "HELLO $NAME"
Run Code Online (Sandbox Code Playgroud)

再见.sh

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

编辑:通过“从事物列表中选择”,我想我是在暗示我的真实用例,它从标准输出中获取任何东西,让我选择一个选项,然后将其传递给其他东西的标准输入...例如:

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
Run Code Online (Sandbox Code Playgroud)

Bra*_*rks 3

感谢4ae1e1,我弄清楚了如何做我想做的事 - 具体来说,如何让我的select_from_list日常工作正常进行:

所以现在我可以做这样的事情:

ls /tmp/ | select_from_list | xargs cat

从中选择一个文件/tmp并对其进行cat。

从列表中选择

#!/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
Run Code Online (Sandbox Code Playgroud)