开发者

Problem with appending to bash arrays

开发者 https://www.devze.com 2023-03-21 14:46 出处:网络
I\'m trying to create an alias that will get all \"Modified\" files and run the php syntax check on them...

I'm trying to create an alias that will get all "Modified" files and run the php syntax check on them...

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+=($filen开发者_Go百科ame)
        fi
    done

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

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

}


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
    :
  done
  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).

0

精彩评论

暂无评论...
验证码 换一张
取 消