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


  • How do I store output of a git command in a Perl array or scalar?
  • Why does my string not split nicely into an array?
  • Ruby create array form git log?
  • store the values from command into an array bash
  • Jenkins Groovy extend properties array
  • How to “-@-expand (”${array}") possibly empty array in Bash when nounset is set?
  • Git Push - Username and password in the remote url
  • Git smudge filter
  • Keep submodule outside working tree
  • How to debug “git pull” taking too much time?
  • Find Git branch name in post-update hook
  • When I pull both a Git submodule repo and its enclosing repo, why do I then have local changes to commit?
  • 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.