how to write a bash shortcut script to enhance your terminal experience

by Eddy Nguyenʉۢ 23 January 2021

duel-of-doves-milktoast-bash-shortcut-script-01

I love shortcuts. If I had to pick the most impactful invention in human history, it would be Ctrl+C and Ctrl+V. We would still be living in caves if we didn't find ways to make our lives easier. Living in caves is what I felt about using the Terminal for a long time. Everything was so hard but felt so... magical at the same time. One day, I got tired of repeatedly bashing my keyboard in, putting down my club, learned bash, and made my first script.

Now, dear reader, gather around the fire (figuratively, of course), and let me tell you about my approach to writing a bash script for shortcuts that got me from the stone age to 2021.

(*) The commands you see in this post are executed on a Mac. If you are using Windows or Linux, you may have to adjust the commands slightly.
(**) I'll stop mentioning cavemen.

🧐 What the bash?

Bash is a command language that allows users to type in text commands to tell the computer to do specific actions. Mac and Linux usually come with bash installed.

If you go to Application > Utilities on a Mac, you will see an app called Terminal.

Open the Terminal, and you will see a black window with white texts - kinda like what the hackers use on TV. This is the command-line interface (CLI) that allows you to run text commands and Bash scripts.

🛠 Starting with the basics

You may have seen something like this before:

# This is an example, do not execute this command.
$ yarn install

In this case, the yarn name of the script, and install is the first parameter. We will want our script to work similarly.

For us, let's say if we try to execute the following command, it will open Netflix in the browser:

# Hell yea - a shortcut to watch Netflix. I'm down!
$ ss tv nf

Executing a command means we type the command into the Terminal and press enter.

Let's create a new file with the following content:

#/bin/bash

function ss( )  {
     echo "Hello World"
     return 0
}

Notes:

  • This file is called a script.
  • The name of the function is ss because we want the command name to be short ( it's a shortcut script after all! ).
  • You can save this anywhere but I normally save all my custom scripts in ~/bin/ss.sh.
  • #/bin/bash is needed at the top so your operating system knows how to run this script i.e. using bash.
  • return 0 is how we tell the terminal that the command has run successfully.
🚗 Executing the script

Normally, if you try to execute the script, it will say that you don't have permission to do so:

 ~ > ~/bin/ss.sh
zsh: permission denied

Bummer, I'm a grown-ass man. No one or nothing should be denying my rights like this. 😤 At this point, we could mess around with script permissions but I prefer sourcing the script for the following reasons:

  • No need to update the script permission. 😌
  • Works regardless of the script location. 😍

You can add the following line at the end of your ~/.zshrc or ~/.bashrc:

# in ~/.bashrc or ~/.zshrc depending on what you use
source ~/bin/ss.sh

Doing this will load the script into the terminals that you open in the future so you can execute ss directly. Now, open a new terminal, type ss into the command prompt, and hit enter, you will see something like this:

~ > ss
Hello world!

✂️ Creating shortcuts

Now we get to the fun part! We want to check the parameters that come after the script name and assign them to an action we want to take. For example, we can update the script to something like this:

function ss( ) {
     case $1 in
          "open")
               vi ~/bin/ss.sh
               return 0
          ;;
          "tv")
                case $2 in
                    "nf")
                         open https://www.netflix.com/
                         echo "Opening Netflix"
                         return 0
                 ;;
                 "az")
                       open https://www.primevideo.com/
                       echo "Opening Amazon Prime"
                       return 0
                 ;;
                 *)
                       open /System/Applications/TV.app
                       echo "Opening Apple TV"
                       return 0
                 ;;
           esac

     ;;
esac

echo "\nERROR - Invalid command\n"
return 1
}

There's quite a bit to take in here but don't worry, here's how it works:

  • There are multiple Bash case statement, each starting with case and ending with esac.
  • $1 and $2 are the first parameter and second parameter (that comes after the script name) respectively.
  • When executed, this function will check if the first parameter is open or tv. If it is tv, it would go into its own case statement, step through the second parameter and check if it is nf or az. *) is to catch all other options.
  • If a correct combination is found, it will execute the code inside the respective block.
  • If no combination is found, return 1 is executed to tell the terminal that an error occurred.

In other words:

  • If the first parameter is open, we will use vi command to make changes to the shortcut file. Remember to start a new terminal after making changes to load the new script!
  • If the first parameter is tv and the second parameter is nf, it will open Nextflix in the default browser.
  • If the first parameter is tv and the second parameter is az, it will open Amazon Prime in the default browser.
  • If the first parameter is tv and the second parameter is anything ( including no second parameter ), it will open the Apple TV app.

Try opening a new bash script and executing the following command and see if it's working:

$ ss tv nf

If it opens Netflix in a new browser, congratulations! You have created your first bash shortcut script.

The above commands are pretty simple but you can add more commands in each block. In another script that I use, I start 5-6 web services locally on my laptop with one command. That is, like, 10000% productivity increase.. or something. Yea. 😏

If you enter an invalid command, you will see an error message:

~ > ss notacommand

ERROR - Invalid commant

🍕 BONUS - Add pizzazz to your script

Error messages just have bad vibes. If I fail to type a command, I want encouragement from my computer, not getting yelled at! If you feel the same way, update the script to the following:

#/bin/bash

function sayStuff( ){
     stuff_to_say=("You may have a fat finger but you also have a freaking fat heart." "Take a       deep breath and try again man. You got this!" "You will stop sucking one day." "Your             command is invalid. But you are valid.")
     length=${#stuff_to_say[@]}
     random=$$$(date +%s)

     random_stuff=${stuff_to_say[$random % $length + 1]}

     echo "\nERROR - Invalid command"
     echo "$random_stuff\n"
}

function ss( ) {
     case $1 in
          "tv")
                    case $2 in
                         "nf")
                              open https://www.netflix.com/
                              return 0
                         ;;
                         "az")
                              open https://www.primevideo.com/
                              return 0
                         ;;
                         *)
                              open /System/Applications/TV.app
                              return 0
                        ;;
                   esac

         ;;
         "open")
               vi ~/bin/ss.sh
               return 0
         ;;
     esac

     sayStuff
     return 1
}

sayStuff is a function that picks one of the few given quotes to cheer you up every time you make a mistake. For me, some aggressive positivity is exactly what I want to hear during trying times:

~ > ss notacommand
ERROR - Invalid command
Your command is invalid. But you are valid.

~ > ss notacommand
ERROR - Invalid command
You have a fat finger but you also have a freaking fat heart.

~ > ss notacommand
ERROR - Invalid command
Take a deep breath and try again. You got this!

~ > ss notacommand
ERROR - Invalid command
You will stop sucking one day.

🙏 Summary

Writing a bash shortcut script is a fun way to get used to scripting as well as saving yourself from typing too much. Do you have other ways that make your daily workflows easier? I would love to hear from you. 🙂

The full code example is available on GitHubIf you have any questions, comments or would like to chat, feel free to reach out via our duel of doves community.

join us

duel of doves is a curated community, created to encourage thought-provoking discussions through connecting and collaborating with like-minded people. A professional online home away from home, sans the office politics, where we can be ourselves and get sh*t done.

subscribe

Get the duel of dove’s wrap-up sent directly to your inbox.

Follow us on instagram