Learn Bash Scripting: A Beginner's Guide to Writing Scripts in Bash

Learn Bash Scripting: A Beginner's Guide to Writing Scripts in Bash

Bash scripting allows you to automate tasks and customize your Linux environment without having to dig into complex programming languages. This beginner's guide will walk you through the basics of writing bash scripts step-by-step.

What is Bash Scripting?

A bash script is a plain text file containing a series of shell commands. Anything you can run normally on the command line can be put into a bash script which is then executed by the shell.

For example, you can have a script that greets you when you log in to a server. Or one that backs up your important files to external storage every night. Complex programs can be written by breaking things into modular bash scripts.

Scripts are interpreted by Bash and don't require compilation. They run on most Linux distributions and macOS. You just write a script once and can execute it repeatedly.

Why Use Bash Scripting?

Here are some of the key reasons why bash scripting is worth learning:

  • Automation - Script once, execute repeatedly. Save time on repetitive tasks.

  • Customization - Tailor your environment and commands exactly how you want.

  • Portability - Scripts run on all Linux/macOS systems without rewriting.

  • Power - Do complex tasks beyond what you can do on one line.

  • Convenience - Quick and easy to write/edit scripts. No compilation is needed.

Writing Your First Script

Let's create a simple script to print "Hello World" and learn the basics:

  1. Open a new plain text file called hello.sh in your preferred text editor like Vim, VS Code, etc.

  2. Add the shebang pointing to the bash interpreter:

     #!/bin/bash
    
  3. Add the following line:

     echo "Hello World"
    
  4. Save the file and exit the editor.

  5. Open your terminal if you don't have it open already, and navigate to the directory where you saved the script using cd directory_name.

  6. To execute the script, run:

     bash hello.sh
    

You should now see the text "Hello World" printed in your terminal. Congratulations - you just wrote your first bash script!

While very simple, this example illustrates core concepts like:

  • #.sh extension indicating a bash script

  • echo command to print output

  • Executing with bash script_name

N/B

There is a second way in which we can write bash scripts and it involves the use of a shebang line.

Understanding the Shebang

The shebang line specifies the interpreter that should be used to execute the script. For bash scripts, it is typically:

#!/bin/bash

When you execute a script, the system looks at the first line to determine the interpreter to use. The #! characters mark it as a shebang.

Here are some key reasons to use a shebang in bash scripts:

  • Portability - The script will work on any Linux/Unix-like system where bash is located at /bin/bash.

  • Clarify language - Removes ambiguity by explicitly declaring this is a bash script.

  • Allows execution - Scripts without a shebang may not run. The shebang enables execute permission.

  • Calls right interpreter - Ensures the script calls the correct bash executable, not another shell.

For example, a simple hello world script would look like:

#!/bin/bash

echo "Hello World"

And you can run it like:

./hello.sh

The shebang must be the absolute first line in the file, without any blank lines above it.

Some other guidelines around using a shebang:

  • Use #!/usr/bin/env bash for more portability if the bash is not at /bin/bash.

  • Make sure to use Unix line endings (LF), not Windows (CRLF) if copying the script between systems.

  • Set the execute permission on the script file with chmod +x script.sh for ease of execution.

  • For BASH specifically, rather than a generic shebang, use #!/bin/bash to enable Bash-specific functionality.

Generally, it is considered a best practice to start bash scripts with a shebang like #!/bin/bash for portability, correct execution, and interpretation.

Now let's learn some key building blocks to write more useful bash scripts.

Variables

Variables allow you to store data and reference it throughout your script. They can hold numbers, text, filenames, and more.

To define a variable, just specify the variable name followed by an = with no spaces around it, then the value to assign:

username="John"

To reference the value stored in a variable, prepend it with $ like:

echo "Username is: $username"

There are also special built-in variables like $0 for the script name or $1 for the first argument passed to a script.

Conditions

Conditions allow you to check information and make decisions by executing different codes based on the result. The primary conditional is the if statement:

count=10
if [ $count -gt 5 ]; then
  echo "Count is greater than 5"
fi

The [ ] brackets contain a test condition that checks if the count is greater than 5. Other common tests include string comparisons and file checks:

if [ "$filename" = "script.sh" ]; then
  echo "File is script.sh"
fi

Loops

Loops allow you to repeat the same block of code numerous times. A for loop iterates over a list:

for username in John Amy Jessica; do
  echo "Hello $username"
done

A while loop executes as long as a condition is true:

count=1
while [ $count -le 5 ]; do
  echo $count
  count=$((count+1))
done

There are also until loops that run until a condition becomes true, along with ways to exit a loop using break.

Functions

Functions allow you to group a sequence of commands for reuse and abstraction:

greeting () {
  echo "Hello $1"
}

greetings "John"
greetings "Amy"

Functions can accept arguments like $1 and return a result using return. You can store reusable pieces of code in functions to call whenever needed.

Summary

Now you have a basic understanding of how to write simple bash scripts using core building blocks like variables, conditions, loops, and functions.

Bash scripting is very useful for automating tasks, customizing your environment, and unlocking the power of the Linux command line. As you write more advanced scripts, you can refer to this guide to refresh the syntax.

Check out the next articles in this series for how to handle user input, debug scripts, write modular code, and more. Happy scripting!

Read: The Advantage of Using #!/usr/bin/env bash Over #!/bin/bash