这里的多行字符串只产生一行

时间:2011-12-08 09:20:46

标签: bash

我需要在while-do循环中处理一组stings,计算一个值并在循环外使用它。起初我写了这段代码:

git diff-index --cached HEAD | while read -r LINE; do
   ...
done

但是,当然,它没有保留内部变量值。然后,根据我在这里找到的建议,我使用了输入重定向:

while read -r LINE; do
...
done <<<$(git diff-index --cached HEAD)

它保留内部变量值,但还有另一个问题 - 由于我不理解的原因,循环只执行一次。我非常确定输入中有多行,并且第一个变体在这方面工作正常。

有人可以解释一下,第二个变种有什么问题吗?也许,我错误地使用重定向?

2 个答案:

答案 0 :(得分:8)

你走在正确的轨道上,你只需要在git生成的输出周围加上引号,以便将其正确地视为单个多行字符串:

while read -r LINE; do
...
done <<< "$(git diff-index --cached HEAD)"

FWIW,以下是一些示例,用于演示此处字符串的引号差异:

# "one" is passed on stdin, nothing happens
# "two" and "three" are passed as arguments, and echoed to stdout
$ echo <<< one two three
two three

# "one" is passed on stdin, gets printed to stdout
# "two" and "three" are passed as arguments, cat thinks they are filenames
$ cat <<< one two three 
cat: two: No such file or directory
cat: three: No such file or directory

# "one two three" is passed on stdin
# echo is invoked with no arguments and prints a blank line
$ echo <<< "one two three"

# "one two three" is passed on stdin
# cat is invoked with no arguments and prints whatever comes from stdin
$ cat <<< "one two three"
one two three

答案 1 :(得分:3)

您正在使用<<<,希望将发送到该命令。你需要

done < <(git ...)

这会创建一个“文件”,用作read的输入。