Bash alias & function tricks

adamlarosa

Adam La Rosa

Posted on April 5, 2020

Bash alias & function tricks

Spending some time on the command line you tend to want to find some shortcuts. Take Rails for example. Key information is spread all about! Migrations, controllers, config files, all neatly organized in the directory tree. But if I wanted to take a quick peek at my routes, I'd have to type out...

cat config/routes.rb

...or the Models...

cat app/models/*

...which at first glance doesn't seem so bad. But when checking that info constantly a shorter solution is desired. Enter the alias.

Basically an "alias" is a short-cut or code-word for a command you'd like to enter into the terminal. With the quick command:

alias routes="cat config/routes.rb"

All I would need to do now is type "routes" into the terminal and it would have the same result as typing out "cat config/routes"

This is great for displaying the contents of one file, or many files in one directory, but what if I'd like to see multiple files across multiple directories? Enter the function.

Shell "scripts" or "functions" work the the same manner as an alias, but for multiple lines of code. My controllers for example are spread across a few different directories. By entering the command:

function controls {

you're brought to a new ">" prompt. It's here where you can enter the commands you'd like executed. In my case to display the controller files in two separate directories I'd enter:

function controls {
> cat app/controllers/*
> cat app/controllers/api/v1/*
}

Now when I want to quickly see the content of the controllers, all I'd need to type is "controls"

These changes will be temporary to your bash session. If you'd like the alias or function to be permanent they will have to be added to your .bash_profile.

💖 💪 🙅 🚩
adamlarosa
Adam La Rosa

Posted on April 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related