DEV Community

Daniel Mayovsky
Daniel Mayovsky

Posted on

Local Aliases in Bash

Quick story

Recently, I started learning Rust. So I was running a lot of cargo check and cargo run and cargo build commands. I wanted to shorten that to ccheck and crun and stuff like that.

Except, commands like that already exist on my machine. I never need them in the Rust project, so I would like to reassing those commands to just these little aliases.

Why this article exists

There's no way to setup a "local alias" command. If alias is defined in my bash profile, it will be used everywhere. So I created a little hack that works for me, and will probably work for you


So, the way to do that, is through Bash functions. In the bash function we can check in which directory we currently are, and take action accordingly.

function ccheck(){
    if [[ $PWD == "/home/daniel/rust-projects/" ]]; then
        # if you are in this folder, execute this command
        cargo check;
        # return stops the function, and it won't reach the ccheck call later in this function
Enter fullscreen mode Exit fullscreen mode

But the problem that you face immediately, is that the later ccheck, the "actual one", is going to Halt your bash session, because it will be stuck in recursion.

To stop that from happening you just have to prepend command before the command that you want to execute. That way, you won't call the function, but the actual command.

function ccheck(){
    # stuff...

    command ccheck;
Enter fullscreen mode Exit fullscreen mode

Now what?

A better way of comparing a directory is against a regex. But since our little directory is not that complicated (or cargo runs anywhere in the project, hehe), we can replace regex with simple wildcard comparison

if [[ $PWD == *"rust-projects"* ]]; then
    # ...
Enter fullscreen mode Exit fullscreen mode

This will make this alias work anywhere within that directory.

Hope that helped you :)

Top comments (1)

kopseng profile image
Carl-Erik Kopseng

Actually, I found your article when searching for "local bash alias", as autoenv and direnv only supports environment variables, but your article actually pointed me to a more flexible general solution than what you posted!

If you change your function to this:

function npm(){ if [[ -z "$NPMBIN" ]]; then $(which npm) $@; else $NPMBIN $@; fi; }
Enter fullscreen mode Exit fullscreen mode

you can for instance use pnpm as your local npm if the NPMBIN variable is set to point to a local install of that. This is so easy to achieve if you install direnv and do

echo 'export NPMBIN="$(npm bin)/pnpm"' >> ~/my/dev/folder/.envrc
Enter fullscreen mode Exit fullscreen mode

This will make sure you use pnpm in my/dev/folder and npm everywhere else.