2015-05-07 31 views
2

我尝试建立一个Git准备提交 - 味精勾,提供了混帐的bash下面的输出(的mingw32):猛砸字符串连接不起作用 - CONCAT的结果是空

<file1>: 
- 
<file2>: 
- 
... 

而且

#!/bin/bash 
git diff --cached --name-status | while read line; do echo $OUTPUT$line$':\n - \n'; done 

的伟大工程

git diff --cached --name-status打印<mode>\t<filePath>索引中的每个文件都变了。

但是当我做

#!/bin/bash 
git diff --cached --name-status | while read line; do OUTPUT=$OUTPUT$line$':\n - \n'; done 
echo $OUTPUT 

#!/bin/bash 
git diff --cached --name-status | while read line; do OUTPUT+=$line$':\n - \n'; done 
echo $OUTPUT 

$OUTPUT是空

这也能正常工作

COUNTER=0 
     while [ $COUNTER -lt 10 ]; do 
      TEST+=$COUNTER$':\n' 
      let COUNTER=COUNTER+1 
     done 
echo $TEST 

我在做什么错?

解决

#!/bin/bash 
git diff --cached --name-status | { 
while read line; do 
    output=$output$var$':\n - \n' 
done 
echo "$output" > $1 
} 
+0

什么是'git的差异--cached --name-status'的输出?如果你编辑你的问题给我们看,这将是有帮助的。 –

回答

2

由于您使用的是管道,该while循环在子shell中运行,因此当子shell退出时,它的变量与它消失。你留下的$OUTPUT变量从壳是空的。

你必须确保你建立在父shell OUTPUT:

while read line; do 
    OUTPUT+=$line$':\n - \n' 
done < <(git diff --name-status) 
echo "$OUTPUT" 

或使用“lastpipe”设置为在当前shell中运行管道的最后一个命令(作业控制需要被关闭)

set +m; shopt -s lastpipe 
git diff --name-status | while read line; do OUTPUT+=$line$':\n - \n'; done 
echo "$OUTPUT" 

或者,输出在子shell变量

git diff --name-status | { 
    while read line; do OUTPUT+="$line"$':\n - \n'; done 
    echo "$OUTPUT" 
} 

其他说明:

  • 如果要保留所有这些换行符,则需要引用"$OUTPUT"
  • 摆脱使用UPPERCASEVARIABLES的习惯:保留为shell保留的那些。
+0

前两种解决方案在mingw32 bash中不起作用。第三个很好。 – BlackEye

1

根本不需要建立变量OUTPUT。只要在读取输入时编写输出即可。 (使用printf是一个小更清洁和更标准比使用echo

git diff --cached --name-status | while read line; do 
    printf '%s:\n - \n' "$line" 
done 
+0

我使用了变量输出,因为我需要将输出写入$ 1中给出的文件。所以在循环结束后,我将echo重定向到$ 1。 – BlackEye

+1

您可以将循环的输出重定向到文件。 '而...;做...;完成>“$ 1”'。 – chepner

+0

@BlackEye,比我的解决方案更好 –