我需要在while-do循环中处理一系列stings,计算一个值并在循环外使用它.起初我写了这段代码:
git diff-index --cached HEAD | while read -r LINE; do
...
done
Run Code Online (Sandbox Code Playgroud)
但是,当然,它不保留内部变量值.然后,根据我在这里找到的建议,我使用了输入重定向:
while read -r LINE; do
...
done <<<$(git diff-index --cached HEAD)
Run Code Online (Sandbox Code Playgroud)
它保留了内部变量值,但还有另一个问题 - 由于我不理解的原因,循环只执行一次.我非常确定输入中有多行,并且第一个变体在这方面工作正常.
有人可以解释一下,第二个变种有什么问题吗?也许,我使用重定向不正确?
Mar*_*tin 10
您处于正确的轨道上,您只需要在生成的输出周围加上引号,git
以便将其正确地视为单个多行字符串:
while read -r LINE; do
...
done <<< "$(git diff-index --cached HEAD)"
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
您正在使用<<<
,它期望将一个单词发送到命令。你需要
done < <(git ...)
Run Code Online (Sandbox Code Playgroud)
这将创建一个用作 的输入的“文件” read
。