Bash – Why doesn’t this regex work

bashregular expression

I want to look at the output of git status -s to determine whether there are any untracked files in the tree. I tried the following test, but the regex doesn't match. Why not?

$ git status -s
## master
 M updated-file
?? new-file
$ [[ $(git status -s) =~ ^\?\? ]] || echo "no match"
no match

I'd also like to be able to test for added/modified/deleted files in the same way. I'd normally just use something like ^\s*[AMD] for this purpose, but this doesn't work either. What gives?

Best Answer

You're matching against the whole string, not each line of the string, as such you're really testing against ## in that regex.

grep is a better choice for this:

if ! git status -s | grep -q '^??'; then
    echo "no match"
fi

As requested, you can do the same for added/modified/deleted:

git status -s | grep '^ *[AMD]'

You might also want to look into git status --porcelain (an option that first appeared in 1.7.0), which is more oriented towards parsing.

Related Question