附加到bash数组的问题

jon*_*ohn 2 arrays git bash

我正在尝试创建一个别名,它将获取所有"已修改"的文件,并对它们运行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

}
Run Code Online (Sandbox Code Playgroud)

gle*_*man 8

正如Wrikken所说,while体在子shell中运行,因此当子shell结束时,对filearray数组的所有更改都将消失.我想到了几种不同的解决方案:

进程替换(可读性较差但不需要子shell)

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

使用命令分组在子shell中使用修改后的变量

git diff --name-status | {
  while read line; do
    :
  done
  echo "${filearray[@]}"
}
# filearray is empty here
Run Code Online (Sandbox Code Playgroud)