Henry Woody
Henry Woody

Reputation: 15662

Check if file exists in any directory in path or if current directory is in a git project

I'm working on adding a short command to my .zshrc file that will call clear, ls, and git status. The git status command should only be called if the current directory is part of a git project.

So far I have a version that works, but only if the .git file is actually in the current directory, so only in the root directory of the project. That looks like this:

alias cl="clear && ls && if [ -e .git ]
then
    git status
fi"

I'm wondering if there is a way to check if there is a .git file in any parent directory of the current directory—or if there's another way to accomplish this.

Thanks!

Upvotes: 0

Views: 460

Answers (1)

larsks
larsks

Reputation: 311625

You don't need to check if there exists a .git directory. Git already does this for you. If you want to know whether your current directory is part of a git repository, just run:

git rev-parse --is-inside-work-tree

The exit code will tell you whether your in a directory that is part of a git repository. That makes your alias look something like:

alias cl="clear && ls && if git rev-parse --is-inside-work-tree 2> /dev/null
then
  git status
fi" 

Upvotes: 5

Related Questions