Find Common Commands In 2 Seconds

By: Ryan Kienstra on: December 8, 2014  in: Bash, Programming

It’s hard to remember all of the commands and snippets you use.

And looking them up from a file takes you out of your “flow.”

But if you’re at the bash prompt, here’s how to find your commands in 2 seconds.

For example, I have a sed command that I use to remove the space before semicolons.

By entering sc sed, I’ll see it in the first line of output:
command line

Here’s how to maintain a file with your favorite commands. And how to find a command by only typing sc

Step 1

Keep a file with your common commands in it.

Let’s say yours is at ~/Documents/system_setup/my_commands.txt

Step 2

Add a command to it:

To write it to the bottom of your my_commands.txt file:

echo 'foo command' >> `locate my_commands.txt`

To enter it manually:

emacs `locate my_commands.txt`

Make sure to use the backticks.

Step 3

Add a function and alias to your  ~/.bashrc file.

Be careful with this. You could crash your command prompt if you do this wrong.

You might want to save a backup of the .bashrc file:

 cp ~/.bashrc ~/.bashrc_backup~

Put this code in your ~/.bashrc file:

searchMyCommands() {
  grep -i $1 ~/Documents/system_setup/my_commands.txt
}

alias sc=searchMyCommands

In the searchMyCommands() function, the file name should be the one where you stored your commands.

Caveat: Instead of using ~/.bashrc, you may have a separate file for user functions.

If you see something like source ~/.bashrc_user_custom in your ~/.bashrc file, you might use the ~/.bashrc_user_custom file instead.

How It Works

By entering alias sc=searchMyCommands, any time you enter sc at the bash prompt, you’ll call the function searchMyCommands().

The searchMyCommands() function takes whatever argument you entered after sc as the parameter $1.

The grep command prints each line in your my_commands.txt file that has the term. The -i flag means case-insensitive; you can use upper or lower case.

Next Step

You could also write a function to add commands to your my_commands.txt file.

Then, this bash command would add ‘my_new_command’ to your list:

add_sc 'my_new_command'

What do you do to make your programming easier? Do you have a way to find common commands?

Add your comment below.

  • This field is for validation purposes and should be left unchanged.

Leave a comment

Get Free Updates

  • This field is for validation purposes and should be left unchanged.