Problem with appending to bash arrays

I’m trying to create an alias that will get all “Modified” files and run the php syntax check on them…

function gitphpcheck () {


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

        if [[ $line =~ ^M ]]
            filename="`echo $line | awk '{ print $2 }'`"
            echo "$filename" # correct output

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

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


  • Why does my string not split nicely into an array?
  • Jenkins Groovy extend properties array
  • store the values from command into an array bash
  • How to “-@-expand (”${array}") possibly empty array in Bash when nounset is set?
  • Git: Getting total numbers of uncomitted lines in a repo
  • How do I ignore a certain file type in a certain directory and its sub-directory in Git?
  • git fsck: how --dangling vs. --unreachable vs. --lost-found differ?
  • What's the difference between git reflog and log?
  • Gitlabs upgrade: getting 500 error on certain pages
  • How to link folder from a git repo to another repo?
  • 2 Solutions collect form web for “Problem with appending to bash arrays”

    As Wrikken says, the while body runs in a subshell, so all changes to the filearray array will disappear when the subshell ends. A couple of different solutions come to mind:

    Process substitution (less readable but does not require a subshell)

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

    Use the modified variable in the subshell using command grouping

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

    You’ve piped | things to while, which is essentially another process, so the filearray variable is a different one (not the same scope).

    Git Baby is a git and github fan, let's start git clone.