Why not using exit codes? If a git repository exists in the current directory, then git branch
and git tag
commands return exit code of 0 (even if there are no tags or branches); otherwise, a non-zero exit code will be returned. This way, you can determine if a git repository exist or not. Simply, you can run:
git tag > /dev/null 2>&1
Advantage: Portable. It works for both bare and non-bare repositories, and in sh, zsh and bash.
Explanation
git tag
: Getting tags of the repository to determine if exists or not.
> /dev/null 2>&1
: Preventing from printing anything, including normal and error outputs.
TLDR (Really?!): check-git-repo
As an example, you can create a file named check-git-repo
with the following contents, make it executable and run it:
#!/bin/sh
if git tag > /dev/null 2>&1; then
echo "Repository exists!";
else
echo "No repository here.";
fi