我正在尝试创建一个别名,它将获取所有“修改”的文件,并对它们运行php语法检查…

function gitphpcheck () {

    filearray=()

    git diff --name-status | while read line; do

        if [[ $line =~ ^M ]]
        then
            filename="`echo $line | awk '{ print $2 }'`"
            echo "$filename" # correct output
            filearray+=($filename)
        fi
    done

    echo "--------------FILES"
    echo ${filearray[@]}

    # will do php check here, but echo of array is blank

}

最佳答案

正如wrikken所说,while主体运行在一个子shell中,因此当子shell结束时,对filearray数组的所有更改都将消失。想到了两种不同的解决方案:
Process substitution(可读性较差,但不需要子shell)

while read line; do
  :
done < <(git diff --name-status)
echo "${filearray[@]}"

使用command grouping
git diff --name-status | {
  while read line; do
    :
  done
  echo "${filearray[@]}"
}
# filearray is empty here

关于arrays - 附加到bash数组的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6766434/

10-13 06:39