How to write a Bash shortcut script to enhance your terminal experience
Tags: bash, beginners
Published: 2021-01-26 21:56: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**  

![Screen Shot 2021-01-22 at 11.41.58 pm](https://dev-to-uploads.s3.amazonaws.com/i/k4vqj6r3vwe2t4artrcu.png) 

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 (including Bash commands and scripts).


## 🛠 Starting with the basics

You may have seen something like this before:

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

In this case, `yarn` is the command name, and `install` is the first parameter. We will want our Bash command to work in a similar way. For us, let's say if we execute the following command, it will open Netflix in the browser:

```bash
# 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 return/enter.

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

```bash
#/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`. For our script, we can save it as `~/bin/ss.sh`.
- `#/bin/bash` is needed at the top so your operating system knows how to run this script i.e. using Bash.
- If this function is executed, it will print "Hello World" in the terminal.
- `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 by typing in the path to the script and hit return/enter, it will say that you don't have permission to do so:

![Screen Shot 2021-01-21 at 10.17.42 pm](https://dev-to-uploads.s3.amazonaws.com/i/44pxcaabupzxhy295wky.png)

😤 Hmm, I'm a grown-ass man. No one or nothing can "permission denied" me like this. Let's find a way to fix this.

At this point, we could mess around with script permissions but I prefer sourcing the script for many reasons:

- No need to update the script permission. 😌
- The function name i.e. `ss` can be used as the command name. 🥰
- The script works regardless of its location. 😍

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

```bash
source ~/bin/ss.sh
```

Doing this will load the script into the terminals that you open in the future so you can execute the `ss` command directly. 

Now, open a new terminal, type `ss` into the command prompt, and hit return/enter, you will see something like this:

![Screen Shot 2021-01-21 at 10.34.27 pm](https://dev-to-uploads.s3.amazonaws.com/i/i0h7c7etf3zyq05rty1m.png)
 
## ✂️ Creating shortcuts

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

```bash
#/bin/bash

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 statements](https://linuxize.com/post/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:

![Screen Shot 2021-01-21 at 11.05.51 pm](https://dev-to-uploads.s3.amazonaws.com/i/md57haop5yurkuu6fuyk.png)
 

## 🍕 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:

```bash
#/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 enter an invalid shortcut combination. For me, some aggressive positivity is exactly what I want to hear during trying times:
- "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."

![Screen Shot 2021-01-21 at 11.16.30 pm](https://dev-to-uploads.s3.amazonaws.com/i/q2fuy9wy9vaznxgqe752.png)
 
## 🙏 Summary

Writing a Bash shortcut script is a fun way to get used to scripting as well as saving yourself from typing too much ( everyone hates that right? ). 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 GitHub: https://github.com/eddeee888/topic-simple-bash