CodeNewbie Community 🌱

Cover image for How to write a Bash shortcut script to enhance your terminal experience
Eddy Nguyen
Eddy Nguyen

Posted on • Originally published at duelofdoves.com

How to write a Bash shortcut script to enhance your terminal experience

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

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:

# This is an example, do not execute this command.
$ yarn install
Enter fullscreen mode Exit fullscreen mode

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:

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

(*) 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:

#/bin/bash

function ss() {
  echo "Hello World"
  return 0
}
Enter fullscreen mode Exit fullscreen mode

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

😀 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:

source ~/bin/ss.sh
Enter fullscreen mode Exit fullscreen mode

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

βœ‚οΈ 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:

#/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
}
Enter fullscreen mode Exit fullscreen mode

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

  • There are multiple Bash case statements, 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
Enter fullscreen mode Exit fullscreen mode

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

πŸ• 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
}
Enter fullscreen mode Exit fullscreen mode

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

πŸ™ 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

Top comments (1)

Collapse
 
thomas43222 profile image
thomas43222

Open a text editor: Start by opening a text editor of your choice. You can use the built-in text editors like nano or vi/vim, or any other text editor you prefer.

Create a new file: Create a new file in the text editor and give it a meaningful name, such as shortcuts.sh. The .sh extension indicates that it's a Bash script.

Declare the script's shebang: Begin the script by declaring the shebang, which specifies the interpreter for executing the hydrogen script. For Bash scripts, the shebang line should be #!/bin/bash.

Define your shortcuts: Below the shebang line, you can start defining your shortcuts. Each shortcut is essentially a function or an alias that encapsulates the desired command or commands.