我试图让bash处理来自stdin的数据,但没有运气。我的意思是以下工作都不做:

echo "hello world" | test=($(< /dev/stdin)); echo test=$test
test=

echo "hello world" | read test; echo test=$test
test=

echo "hello world" | test=`cat`; echo test=$test
test=

我希望输出为test=hello world。我尝试在“$test”周围加上“”引号,但也不起作用。


当前回答

Bash 4.2引入了lastpipe选项,通过在当前shell(而不是子shell)中的管道中执行最后一条命令,允许代码按编写的方式工作。

shopt -s lastpipe
echo "hello world" | read test; echo test=$test

其他回答

我不是Bash方面的专家,但我想知道为什么没有人提出这个建议:

stdin=$(cat)

echo "$stdin"

一行程序证明它对我有效:

$ fortune | eval 'stdin=$(cat); echo "$stdin"'

Use

IFS= read var << EOF
$(foo)
EOF

你可以像这样诱使read从管道中接受:

echo "hello world" | { read test; echo test=$test; }

或者写一个这样的函数:

read_from_pipe() { read "$@" <&0; }

但这没有意义——你的可变任务可能不会持久!管道可以生成子shell,其中环境是按值继承的,而不是按引用继承的。这就是为什么read不打扰管道的输入——它是未定义的。

仅供参考,http://www.etalabs.net/sh_tricks.html是一个漂亮的cruft收集必要的战斗奇怪和不兼容的伯恩炮弹,sh。

我认为您正在尝试编写一个shell脚本,可以从stdin输入。 但是当您尝试内联执行时,您在尝试创建test=变量时迷失了方向。 我认为内联执行它没有多大意义,这就是为什么它不能以您期望的方式工作的原因。

我试着减少

$( ... | head -n $X | tail -n 1 )

从不同的输入中得到特定的一行。 所以我可以输入…

cat program_file.c | line 34

所以我需要一个小shell程序能够从stdin读取。就像你一样。

22:14 ~ $ cat ~/bin/line 
#!/bin/sh

if [ $# -ne 1 ]; then echo enter a line number to display; exit; fi
cat | head -n $1 | tail -n 1
22:16 ~ $ 

好了。

Bash 4.2引入了lastpipe选项,通过在当前shell(而不是子shell)中的管道中执行最后一条命令,允许代码按编写的方式工作。

shopt -s lastpipe
echo "hello world" | read test; echo test=$test

我想要类似的东西——一个可以解析字符串的函数,可以作为参数或管道传递。

我提出了一个解决方案如下(工作作为#!/bin/sh和作为#!/bin/bash)

#!/bin/sh

set -eu

my_func() {
    local content=""
    
    # if the first param is an empty string or is not set
    if [ -z ${1+x} ]; then
 
        # read content from a pipe if passed or from a user input if not passed
        while read line; do content="${content}$line"; done < /dev/stdin

    # first param was set (it may be an empty string)
    else
        content="$1"
    fi

    echo "Content: '$content'"; 
}


printf "0. $(my_func "")\n"
printf "1. $(my_func "one")\n"
printf "2. $(echo "two" | my_func)\n"
printf "3. $(my_func)\n"
printf "End\n"

输出:

0. Content: ''
1. Content: 'one'
2. Content: 'two'
typed text
3. Content: 'typed text'
End

对于最后一种情况(3.),您需要键入,按enter和CTRL+D结束输入。