DEV Community

loading...

Local Aliases in Bash

weirdmayo profile image Daniel Mayovsky ・2 min read

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

Solution

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
        return;
    fi
    ccheck;
}

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;
}

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
    # ...
fi

This will make this alias work anywhere within that directory.

Hope that helped you :)

Discussion

pic
Editor guide