• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (deprecated)
You are here: Home / Dev Tips / cd in script without polluting previous directory

cd in script without polluting previous directory

Last updated on October 5, 2023 by Sal Ferrarello

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
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on X (Twitter)Share on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Computing, Dev Tips, Solution Tagged With: command line, zsh

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in