Skip to main content

Command Palette

Search for a command to run...

How to Write Your First Bash Script (and Why You Absolutely Should)

Updated
7 min read
How to Write Your First Bash Script (and Why You Absolutely Should)
S

Curious CS Student exploring tech that fascinates me. Currently Identify as WEB Developer.

Whether you're deep in the tech world or just watching from the sidelines, you might have come across the term “Bash Scripting”. And like many (including me!), you might’ve thought it’s some hacker-like stuff that a riced-out Arch Linux user plays with.

While not entirely wrong, Bash Scripting is an amazing tool that opens the door to creating powerful automations and configurations, all while gently easing you into the world of command-line interface (CLI).

So, What is Bash Scripting?

Simply put, Bash Scripting is writing a series of commands in a plain text file that the Bash shell can execute.

Think of it as automating the tasks that you’ll normally do on the command line. So instead of typing each command one by one, you write it all down in a script. Whenever you need that task done, just run the script and let it work for you!

These scripts can include:

  • File operations (mv, cp, rm)

  • Loops and conditionals (for, if, while)

  • System commands (top, df, ps)

  • Even calling other programs or scripts

Now mostly these scripts are native to UNIX-based systems like Linux and macOS but if you are a Windows user, you can still harness its power through Git Bash or WSL (Windows Subsystem for Linux).

Why learn Bash Scripting?

Bash Scripting isn’t just some nerdy side-quest, it is also one of the most useful tools a developer can have. It saves time, reduces mistakes, and makes their workflows repeatable.

Here are a few examples of how different folks use it:

🖥️Backend / DevOpsFrom pulling code to deploying apps and monitoring servers
🛠️System AdministratorsUser management, log rotation, and scheduling tasks for consistent functioning
🧪Data ScientistsScheduling cron jobs to scrape real-time data; Download, extract & clean large datasets, chain python scripts for an end-to-end workflow and more
🌐Cloud EngineersScripts to spin up servers, install software, configure networking and keep an eye on server health

How I got introduced to Bash Scripting

Lately I’ve been working on a few React projects. If you have done that too, you can relate to how much of a chore setting up a new React project can be. I use Vite, so my workflow looks like this:

  1. Create a new project.

  2. Select the React template.

  3. cd into the project directory.

  4. Install node modules.

  5. Initialize Git.

  6. If I want to use Tailwind, I have to install Tailwind CSS.

  7. Add it to the dependencies in Vite configuration.

  8. Import Tailwind CSS in index.css.

… and most of it is done using command line.

It got me thinking there must be a way to automate this, and that’s when I learnt about Bash Scripting.

What next? I ran to w3schools and skimmed through the entire Bash Tutorial. Surprisingly, it felt just like any other programming language, with variables, loops, and conditionals working together with system commands.

The script I then created works something like this:

Writing My First Bash Script

After learning the fundamentals and practicing a few examples, I was ready to create my first real automation. I’ll share my process and the script so you can also benefit from it too! :)

  1. Creating a Script File

    • First, create a new directory (e.g., scripts) as It’s ideal to keep all your scripts in a dedicated location.

    • Inside the directory, create a new shell script file (let’s call it newreact.sh). Inside, add this very important first line:

        #!/bin/bash
      

      This is called a shebang, and it tells the system to use Bash shell to execute this script.

  1. Commands to Create a new React Project

     echo "Initializing New React Project ..."
     npm create vite@latest "$1" -- --template react
     cd $1
     npm install
    
    • echo displays text in the CLI so you know what’s going on.

    • $1 is a special variable that holds the first argument provided when running the script, which is the name of your new project.

      With that, your new project will be created with a single command! But we’re not done yet.

  1. Initializing Git and Tailwind

    For this, we will first check if the user wants to use Git and Tailwind CSS by looking for specific keywords in the arguments.

     for arg in "$@"; do
         if [[ "$arg" == "tw" ]]; then
             echo "Installing TailwindCSS ..."
             npm install tailwindcss @tailwindcss/vite
    
             echo "Importing TailwindCSS ..."
             sed -i '1i @import "tailwindcss";' src/index.css
             # for macOS => sed -i '' '1i @import "tailwindcss";' src/index.css
    
             echo "Configuring vite.config.js ..."
    
             grep -q 'tailwindcss' vite.config.js || sed -i '1i import tailwindcss from "@tailwindcss/vite";' vite.config.js
                 # for macOS => sed -i '' '1i import tailwindcss from "@tailwindcss/vite";' vite.config.js
    
             sed -i 's/react()/react(), tailwindcss()/' vite.config.js
         fi
    
         if [[ "$arg" == "git" ]]; then
             echo "Initializing Git ..."
             git init
         fi
     done
    
    • $@ gives you all arguments, which we can iterate over using a for loop and match using if conditions.

    • Notice how the condition starts with if and ends with fi, which is the reverse of if? It’s one of the quirky syntax bits of Bash scripting language that you will not forget easily.

    • sed is a powerful command used to process and manipulate text. We use it here to add statements in index.css and vite.config.js files in order to properly import and initialize Tailwind CSS in our project.

Important Note
Be very careful of where you use whitespaces. It can make or break your code. However, indentations before the statements don’t have any special meaning unlike Python. They are used for code readability.
  1. Finishing up

    Our script is almost done. Now to make our lives easier, we can open up VS Code right after setting up the project.

    Just add code . at the end of the script to open it up in the project directory you just created.

     echo "Setup Complete! Opening VS Code ..."
     code .
     # This assumes you have the code command installed in your system's PATH, which is standard with a VS Code installation.
    

    AND we’re done! ✨

  2. Making this script Executable

    We have written the script, but it can’t be executed just yet as the system still sees it as a regular text file. Let’s make it executable.

    Navigate to the scripts directory in the terminal where you created your script and run this command:

     chmod +x newreact.sh
    
    • chmod stands for “change mode”.

    • +x gives “execute” permission.

  1. Add the Directory to Your PATH

    Our script works now, but typing the entire path, like ~/scripts/newreact.sh is tedious. Simply typing its name should launch it from any directory.

    • To accomplish that we will add our scripts directory to PATH so the system looks for our script in the directory by itself. To do that, run the following command:

      For Bash users:

        echo 'export PATH="$PATH:$HOME/scripts"' >> ~/.bashrc
      

      For Zsh users (macOS):

        echo 'export PATH="$PATH:$HOME/scripts"' >> ~/.zshrc
      
    • To apply the changes, either close and reopen the terminal OR run the following command:

        source ~/.bashrc  # for Bash
        source ~/.zshrc   # for Zsh
      
What is PATH?
The PATH is a list of all the folders the shell looks at when you run a command; think of it as your terminal's address book.
  1. Try It Out

    Navigate to your desired projects directory, and run this command to create a new project:

     newreact.sh my-cool-project git tw
    

Well… What Next?

By now you have learnt about the usage and importance of Bash scripting and even created your own first script. But trust me, it's not the last. You can find an idea or another of a repetitive task that's just begging to be automated.

Seriously, once you start seeing the world through a "scripting lens", you'll see opportunities everywhere.

  • That boring chore of organizing your Downloads folder? Script it.

  • Want to back up your important project files to another drive with one command? Script it.

  • Need to update all your system packages and clean up old files? You guessed it—script it.

Heck, take the script we just built and go wild. Add an option for TypeScript, or maybe one to automatically open the browser. It's your tool now, so make it work for you.

The point isn't to become some elite hacker overnight. It's about making your own life a tiny bit easier, one script at a time.

P.S. Just for fun, comment down below how many times I used the word "script" or "scripting." Even I feel like I went a little overboard! 😆