tags:

views:

357

answers:

4

git - how to tell if a file is git tracked?

In other words: Is git tracking a file?

Update: I should've been clearer. Is there a way to tell if a file is being tracked by running some git command and checking its exit code?

+2  A: 

Try running git status on the file. It will print an error if it's not tracked by git

PS$> git status foo.txt
error: pathspec 'foo.txt' did not match any file(s) known to git.
JaredPar
Wow. I must have been running it on a directory and it acted like it was checking the entire repo. Thanks.
Darvan Shovas
Actually, if I run `git status trackedfile` I get exit code 1 (expected 0 to be useful) but it doesn't give me "error:" in the output. I'd rather parse an exit code than string output.
Darvan Shovas
+2  A: 

EDIT

If you need to use git from bash there is --porcelain option to git status:

--porcelain

Give the output in a stable, easy-to-parse format for scripts. Currently this is identical to --short output, but is guaranteed not to change in the future, making it safe for scripts.

Output looks like this:

> git status --porcelain
 M starthudson.sh
?? bla

Or if you do only one file at a time:

> git status --porcelain bla
?? bla

ORIGINAL

do:

git status

You will see report stating which files were updated and which ones are untracked.

You can see bla.sh is tracked and modified and newbla is not tracked:

# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#
#       modified:   bla.sh
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       newbla
no changes added to commit (use "git add" and/or "git commit -a")
stefanB
Sorry I should've been clearer. Status is okay but I'd rather check an exit code than parse output.
Darvan Shovas
`git status --porcelain` is your friend if you need to parse output by script, have a look at the linked doc it show some other useful options
stefanB
+1  A: 

I don't know of any git command that gives a "bad" exit code, but it seems like an easy way to do it would be to use a git command that gives no output for a file that isn't tracked, such as git-log or git-ls-files. That way you don't really have to do any parsing, you can run it through another simple utility like grep to see if there was any output.

For example,

git-ls-files test_file.c | grep .

will exit with a zero code if the file is tracked, but a exit code of one if the file is not tracked.

Jay Walker
+3  A: 

try:

git ls-files file_name --error-unmatch

will exit with 1 if file is not tracked

hasen j
Thank you, I think that does it
Darvan Shovas