I wanted to write a shell alias to get the Git status of a specific directory (~/code/projectx
). In my first draft, I used cd
to go to the directory, ran git status
, and then ran cd -
to return the original directory I was in. This worked great, except if I then typed cd -
I ended up in ~/code/projectx
(instead of whatever my previous directory was before that). How could I change directories without polluting the previous directory? (so cd -
still works as it did before I ran my alias)
Solution
Use parentheses ()
in your alias
alias projectxgitstatus="(cd ~/code/projectx && git status)"
This runs the command(s) in the parentheses in a subshell so the directory change does not impact our shell session. (Note: we don’t even need to change back to the original directory in our alias).
Pure Git Solution
In solving this issue I found git -C
allows you to pass a path to Git so that Git runs as if it were invoked in that path. e.g.
git -C ~/code/projectx/ status
So I can create the alias (and no subshell is needed)
alias projectxgitstatus="git -C ~/code/projectx/ status"
Summary
Bare Command
Leaves me in the ~/code/projectx
directory 🙁
cd ~/code/projectx && git status
In Subshell
The commands are run in a subshell, when they complete I’m returned to my original shell in the original directory (with cd -
still pointing to the directory it did before this command was run).
(cd ~/code/projectx && git status)
With Git -C
I never leave my current directory so a subshell is not necessary. Git runs as if it were invoked in ~/code/projectx
(and cd -
still points to the directory before this command because I never change directories).
git -C ~/code/projectx/ status
Leave a Reply