Issue
I'm trying to define an alias to cd
me into the git root directory using git rev-parse --show-toplevel
.
Currently I have it as an alias in my .bashrc
, which works fine:
alias gitroot='cd "$(git rev-parse --show-toplevel)"'
But I know that you can run shell commands using git aliases, so I thought I'd move the command into my .gitconfig
to make my files a bit cleaner.
Problem is, I can't figure out why my alias isn't working. Currently I have this under [alias]
in my .gitconfig
:
root = "!sh -c 'cd \"$(git rev-parse --show-toplevel)\"'"
But when I run git root
, I just stay put in the current directory.
I've experimented with other shell aliases and they've worked, e.g. the alias say = "!sh -c 'echo \"$0\"'"
works just fine:
$ git say hello
hello
Though I've noticed that a similar cd
command (cd = "!sh -c 'cd \"$0\"'"
) fails:
~/repos/myproject$ git cd /home/
~/repos/myproject$
I can't figure out if it's something to do with my syntax or if it's a quirk of git aliases that it doesn't support the cd
command, or something else entirely.
If it helps, I'm using Git 1.7.9.5.
Solution
Your shell is invoking Git, and Git is invoking another shell in which to run your cd
command. This command is successful, and this changes the working directory of the child shell, but it does not change the working directory of Git, nor of the parent shell.
In order to do this you need to run the command in your current shell, which means that invoking Git will not be able to accomplish this. You will have to continue using a shell alias.
To illustrate, let's say you have the following shell script called up.sh
:
#!/bin/sh
cd ..
If you execute this script as ./up.sh
then nothing will change from the perspective of your current shell, because cd
was executed in a new shell instance. However, if you execute it as . up.sh
, this instructs your current shell to execute the contents of the file by itself, without spawning a subshell. In that case the current shell's working directory will change.
That's the key difference here. Using a Git alias is similar to the ./up.sh
method, while a shell alias is similar to the . up.sh
method.
Answered By - cdhowie Answer Checked By - Robin (WPSolving Admin)