Streamlining Your Terminal Commands With Custom Bash Functions and Aliases

If you’ve ever found yourself typing out the same long commands over and over again, or if you’ve ever wished you could teleport directly to your favourite directories, then this post is for you.

Before we jump into some useful examples, let’s go over what bash functions and aliases are, and how to set them up.

Bash Functions vs Aliases

A bash function is like a mini script stored in your .bashrc or .bash_profile file. It can accept arguments, execute a series of commands, and even return a value.

On the other hand, an alias is a simple shortcut for a command or a series of commands. It doesn’t handle arguments or complex logic like a bash function, but it’s great for quick and simple shortcuts.

Here’s an example of a bash function:

hello() {
    echo "Hello, $1"
}

And here’s an example of an alias:

alias ll='ls -l'
Read more: Streamlining Your Terminal Commands With Custom Bash Functions and Aliases

To add a custom function or alias, simply add it to your ~/.bashrc file, or ~/.zshrc if using zsh. Don’t forget to source the file after updating it!

Streamlining SLURM Commands

Working with SLURM commands can be a bit cumbersome, particularly if you’re running similar jobs repeatedly. Here’s where bash functions come into play. Let’s take a look at a couple of examples:

slurm_run() {
        srun --clusters=all -p "$1"-debug -D "/data/localhost/not-backed-up/turnbull" --pty /bin/bash
}
slurm_run_gpu() {
        srun --clusters=all --gpus 1 -p "$1"-debug -D "/data/localhost/not-backed-up/turnbull" --pty /bin/bash
}

These functions let you quickly run interactive jobs on slurm, by simply typing slurm_run or slurm_run_gpu followed by the partition name, saving a lot of typing out and remembering of parameters!

Quick Directory Access with Aliases

You might have certain directories that you access frequently. Typing out the full path every time can be a pain. Aliases are a great solution to this – here are a couple examples:

alias data="cd /vols/opig/users/turnbull/Data"
alias projects="cd /data/localhost/turnbull/Projects"

Now, to go to your Data directory, you simply type data. To go to your Projects directory, just type projects. It’s as simple as that!

Monitoring SLURM Jobs

If you’re running a lot of jobs, it’s helpful to keep an eye on their status. Here’s an alias for that:

alias watch_slurm="watch squeue -u turnbull --clusters=all"

Typing watch_slurm will now keep a live update of your SLURM jobs.

Conclusion

Custom bash functions and aliases are powerful tools that can significantly streamline your work in the terminal. They not only save time but also make your commands more readable.

Author