Skip to content

Instantly share code, notes, and snippets.

@yegle
Created December 11, 2012 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yegle/4256080 to your computer and use it in GitHub Desktop.
Save yegle/4256080 to your computer and use it in GitHub Desktop.
bash read varaible
#!/bin/bash
# FAIL!
echo a| read i
echo $i
# WORKS
read i <<<$(echo a)
echo $i
@weynhamz
Copy link

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
Copy link

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