3

I am trying to create a string array of my modified git files so I can use them in a bash program. Sample output:

On branch restructured
Your branch is up-to-date with 'origin/restructured'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified: path/to/file1 
    modified: path/to/file2

I'm tryig to grab the text after modified: but from what I've found grep doesn't support new line so i'm at a loss how I could convert the raw output into something I could work with.

Community
  • 1
  • 1
Nick
  • 9,285
  • 33
  • 104
  • 147
  • 3
    I would suggest starting with `git status --porcelain`, which is specifically geared towards being easy(-er) to parse... – twalberg Mar 25 '14 at 18:21

3 Answers3

8

If you really just want a list of modified files, consider git ls-files -m. If you need something extensible to potentially other types of changes:

git status --porcelain | while read -r status file; do
  case "$status" in 
    M) printf '%s\n' "$file";;
  esac
done
kojiro
  • 74,557
  • 19
  • 143
  • 201
3

How about:

files=(git status | grep '^\s*modified:' | cut -f 2- -d :)

Reading from inside out, that:

  • Passes git status to grep, which
  • looks for lines with modified: on them singularly, then
  • cuts everything after the colon on those lines, then finally
  • puts that into an array assigned to $files
bishop
  • 37,830
  • 11
  • 104
  • 139
1

You are looking at the problem wrong.

Git "status" is a pretty view derived from a number of underlying commands.

The list of "changed" files is retrieved with

$ git diff --name-only --diff-filter=M
modifiedfile.txt

diff-filter can be:

  • A Added files
  • C Copied files
  • D Deleted files
  • M Modified files
  • etc.. check the manual.

You can also try ls-files which supports -d, -m, -a, and -o.

If you are looking for NEW files which are not yet tracked, you can try

$ git ls-files -o
untrackedfile.txt

As a last resort, if you really insist on trying to parse the output from git-status, consider using the '--short' or '--porcelain' output option. --short produces coloured output, which --porcelain avoids.

$ git status --short
 M modifiedfile.txt
?? untrackedfile.txt
Dave
  • 3,193
  • 1
  • 16
  • 14