Auto-alias Your Repos
Kyle Nickel

Kyle Nickel @nickelkr

Joined:
Sep 6, 2018

Auto-alias Your Repos

Publish Date: Jan 25 '20
7 9

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

Comments 9 total

  • Stefan Bauckmeier
    Stefan BauckmeierJan 28, 2020

    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)

    • Kyle Nickel
      Kyle NickelJan 28, 2020

      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.

  • James McNulty
    James McNultyJan 28, 2020

    Try autojump ;)

    • Kyle Nickel
      Kyle NickelJan 28, 2020

      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.

  • Kyle Nickel
    Kyle NickelJan 28, 2020

    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.

  • Piotr Szadkowski
    Piotr SzadkowskiJan 28, 2020

    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
    
  • Klaus Alexander Seistrup
    Klaus Alexander SeistrupJan 29, 2020

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

  • Philidor Green
    Philidor GreenJan 29, 2020

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

  • Peter Luladjiev
    Peter LuladjievJan 29, 2020

    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

Add comment