37

I have a script in one of my iOS apps that should get the git revision hash and put it in the version number. In this script I run git --git-dir="$PROJECT_DIR" show -s --pretty=format:%h for that. However, I get the message that the directory isn't a git repository. If I echo the PROJECT_DIR var and go to the terminal the following works:

cd projectDirPath
git show -s --pretty=format:%h

What doesn't work is:

git --git-dir=projectDirPath show -s --pretty=format:%h

Am I missing something? The documentation states, that I can specify the path to a git repository with --git-dir and the specified path obviously is a git repository as all the git commands work without any problem if I first cd into that path. However if I am not in this path, specifing --git-dir doesn't work.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Michael Ochs
  • 2,846
  • 3
  • 27
  • 33

3 Answers3

49

When using --git-dir, you need to point at the .git folder of your repository. Try:

git --git-dir=projectDirPath/.git show -s --pretty=format:%h

The doc on --git-dir says that:

--git-dir=

Set the path to the repository (".git" directory). This can also be controlled by setting the GIT_DIR environment variable. It can be an absolute path or relative path to current working directory.

I use to have an issue remembering this myself. To help me remember what to do, I try to remember that the option is asking for exactly what it wants: the path to the .git directory (git-dir).

jdhao
  • 24,001
  • 18
  • 134
  • 273
John Szakmeister
  • 44,691
  • 9
  • 89
  • 79
3

You are looking for the git -C command line option.

-C <path>

Run as if git was started in instead of the current working directory. When multiple -C options are given, each subsequent non-absolute -C <path> is interpreted relative to the preceding -C <path>. If <path> is present but empty, e.g. -C "", then the current working directory is left unchanged.

This option affects options that expect path name like --git-dir and --work-tree in that their interpretations of the path names would be made relative to the working directory caused by the -C option. For example the following invocations are equivalent:

git --git-dir=a.git --work-tree=b -C c status
git --git-dir=c/a.git --work-tree=c/b status
Mathieu CAROFF
  • 1,230
  • 13
  • 19
2

Apart of --git-dir, also setting --work-tree may help. For the script, it's good to use relevant environments (it's easier), e.g.

#!/bin/bash -ex
export GIT_WORK_TREE=/path/to/repo
export GIT_DIR=/path/to/repo/.git
git show -s --pretty=format:%h
kenorb
  • 155,785
  • 88
  • 678
  • 743