Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
bash read varaible
#!/bin/bash
# FAIL!
echo a| read i
echo $i
# WORKS
read i <<<$(echo a)
echo $i
@weynhamz

This comment has been minimized.

Copy link

@weynhamz weynhamz commented Dec 11, 2012

Bash 的管道都是在 subshell 中执行的,所以第一个 loop 中的变量不会影响到当前 shell 环境,可以使用语句块,都放到 subshell 去。

echo a b c| { while read i
do
    echo $i
done
echo $i
}
或者使用进程替换

while read i
do
echo $i
done < <(echo a b c)

第二个用 here string 和进程替换其实是一样的。
@weynhamz

This comment has been minimized.

Copy link

@weynhamz weynhamz commented Dec 11, 2012

Bash 4.2 有 lastpipe 选项,开启了就和 ksh 一样了,管道的最后一部分在当前 shell 运行。

shopt -s lastpipe

不小心看到了,进来发发牢骚。另外,竟然不能修改评论,你能修改的话,把上一条的格式调整下吧。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.