15

How to run git commit -m '...' command from another directory?

I edit my file:

vim /home/.../myFile

I add it using:

git add /home/.../myFile

But now, how can I commit the changes?

git commit -m '...' ???
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

3 Answers3

27

You can use git -C <path> <command>. From https://git-scm.com/docs/git/2.4.4

git -C <path> commit -m "Some commit message"

Runs as if git was started in <path> instead of the current working directory.

Oded Peer
  • 2,377
  • 18
  • 25
  • Not true for git commit. From help: -C, --reuse-message – Arkadiusz 'flies' Rzadkowolski Apr 03 '21 at 21:02
  • 3
    It is, true ! Actually, `-C, --reuse-message ` is the `-C` option of `git commit`. But there, we use `-C` option of `git`. In other words : `git -C commit ... ` is not the same as `git commit -C ...`. – Nicolas PERNOT May 07 '21 at 08:37
  • Comments are wrong. You can run `git -C commit ` for example I just run: `git -C syncedConfigs/ commit -m " files`. Great for using with crontab :+) – Minsky Feb 17 '22 at 13:19
23

You can also use the environment variables $GIT_DIR and $GIT_WORK_TREE to the same effect as --git-dir and --work-tree

These are the steps to commit a file when you are in another directory:

git --git-dir=/path/to/my/directory/.git/ --work-tree=/path/to/my/directory/ add myFile
git --git-dir=/path/to/my/directory/.git/ --work-tree=/path/to/my/directory/ commit -m 'something'
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
l4rd
  • 406
  • 3
  • 5
  • 2
    This didn't work for me until I removed the '=' from `--git-dir`. It might need it removed from `--work-tree`, too. Maybe a difference in git versions? – labyrinth Jan 14 '16 at 18:45
0

After commiting everything with the --git-dir parameter there where several files deleted from the repo and I had to recover them. For me the best solution was in a script to do a cd to the other folder and then execute the git commands. Was way less code to write without the parameters in every command.

Martin Cup
  • 2,399
  • 1
  • 21
  • 32