DEV Community

Kyle Nickel
Kyle Nickel

Posted on

Auto-alias Your Repos

If you have all your code repos under a common directory, you can make it so changing your working directory to any of the repos is just entering the name of the repo.

For example, all my code repos are under ~/code:

~ > ls ~/code
bar    foo
Enter fullscreen mode Exit fullscreen mode

By adding a loop for the sub-directories of the common parent inside your shell config, ~/.zshrc in my case, you can automatically create a alias for each of the repo directories:

for repo in $(ls ~/code)
do
  alias $repo="cd ~/code/$repo"
done
Enter fullscreen mode Exit fullscreen mode

Then you need to reload your config:

~ > . ~/.zshrc
Enter fullscreen mode Exit fullscreen mode

Now, if you're in one repo, lets say foo:

~/code/foo/app/models >
Enter fullscreen mode Exit fullscreen mode

You can easily swap over to bar:

~/code/foo/app/models > bar
~/code/bar >
Enter fullscreen mode Exit fullscreen mode

Top comments (9)

Collapse
 
offthecode profile image
Piotr Szadkowski

Hey nc idea, expanded it a little so you can provide more locations

locations=(react sites ios android)

for location in "${locations[@]}"
do
    for repo in $(ls ~/$location)
    do
        alias $repo="cd ~/$location/$repo"
    done
done
Collapse
 
nickelkr profile image
Kyle Nickel

A comment on a different site has given, for zsh, what I believe is the best solution for this:

Set cdpath=($HOME/code) in .zshrc. With auto_cd this allows for the same functionality without creating a bunch of aliases.

Collapse
 
kseistrup profile image
Klaus Alexander Seistrup

What's the thing with “$(ls ~/code)”? Why spawn a subshell, rather than just saying “for repo in ~/code/*”?

Collapse
 
emrox profile image
Stefan Bauckmeier

now you just have to be cautious to not check out any project having a name like a command on your machine. (like git clone https://server/myproject.git ~/code/ls)

Collapse
 
nickelkr profile image
Kyle Nickel

Yeah, that's clearly a risk, but most likely a outlier.

You could always add constraint in the loop to skip the iteration if the command already exists, as well.

Collapse
 
jimmcnulty41 profile image
James McNulty

Try autojump ;)

Collapse
 
nickelkr profile image
Kyle Nickel • Edited

What seems to be a good solution is using cdpath in combination with auto_cd in zsh, should produce the same results without the aliasing.

Collapse
 
luladjiev profile image
Peter Luladjiev

ZSH's plugin Z does almost the same job. It requires you to use the command z in front of the folder name but it does not pollute your shell with aliases e.g. z foo OR z bar

Collapse
 
philidorgreen profile image
Philidor Green

@nickelkr it very handy. I've a slightly better way here