Skip to Content

Bash Scripting Tutorial – Linux Shell Script and Command Line for Beginners

Definition of Bash Scripting

A bash script is a text file containing a sequence of commands designed to be executed by the bash program, which is a Unix/Linux shell.

These commands are processed line by line, allowing for the automation of tasks such as navigating to a specific directory, creating a folder, or launching a process via the command line.

By saving these commands in a script, users can execute the same sequence of actions repeatedly with a single command.

Advantages of Bash Scripting

Bash scripting offers numerous benefits for automating tasks and managing system resources on Unix/Linux systems:

  • Automation: Automate repetitive tasks, saving time and minimizing manual errors.
  • Portability: Run scripts across various platforms, including Unix, Linux, macOS, and Windows through emulators or virtual machines.
  • Flexibility: Easily customize scripts to meet specific needs and combine with other languages or utilities.
  • Accessibility: Write scripts using any text editor and execute them with a built-in shell interpreter on most operating systems.
  • Integration: Integrate scripts with databases, web servers, and cloud services for complex automation tasks.
  • Debugging: Debug scripts with ease using built-in debugging and error-reporting tools.

Overview of Bash Shell and Command Line Interface

The “shell” is a program that provides a command-line interface for interacting with the operating system.

Bash (Bourne-Again SHell) is one of the most commonly used Unix/Linux shells and is the default shell in many Linux distributions.

A shell or command-line interface accepts commands from the user and displays the output. Interactive shells display a prompt, typically a dollar sign `$`, when waiting for user input. The root user’s prompt is indicated by a hash symbol `#`.

While Bash is the focus of this tutorial, other shells like the Korn shell (ksh), C shell (csh), and Z shell (zsh) are also available, each with its own syntax and features.

To determine your current shell type, you can use the ps command:

ps

For example, the output might indicate that you are using the bash shell.

$ ps
PID TTY TIME CMD
6807 pts/0 00:00:00 bash
6841 pts/0 00:00:00 ps

It’s important to note that while “shell” is a broad term that refers to any program that provides a command-line interface, “Bash” is a specific type of shell that is widely used in Unix/Linux systems.

How to Get Started with Bash Scripting

Running Bash commands from the command line is a fundamental skill in Unix/Linux environments. The shell prompt, which looks something like this:

[tocao@howtouselinux ~]$

indicates that you can enter any command after the $ sign and see the output on the terminal.

Generally, commands follow this syntax:

command [OPTIONS] arguments

Let’s discuss a few basic Bash commands and see their outputs. Make sure to follow along:

Basic Bash Commands

  • date: Displays the current date.
    tocao@howtouselinux:~$ date
    Tue Mar 14 13:08:57 PKT 2023
  • pwd: Displays the present working directory.
    tocao@howtouselinux:~$ pwd
    /home/tocao
  • ls: Lists the contents of the current directory.
    tocao@howtouselinux:~$ ls
    check_plaindrome.sh  count_odd.sh  env  log  temp
  • echo: Prints a string of text, or the value of a variable, to the terminal.
    tocao@howtouselinux:~$ echo "Hello bash"
    Hello bash

You can always refer to a command’s manual with the man command. For example, the manual for ls looks like this (image representation not included here):

You can see the options for a command in detail using the man pages.

How to Create and Execute Bash Scripts

Script Naming Conventions

By convention, bash scripts end with the .sh extension. However, scripts can execute without it.

Adding the Shebang

Bash scripts begin with a shebang, a sequence of characters #! followed by the path to the bash shell. This directive is always the first line in the script, indicating to the system that the script should be run in the bash shell.

Example of Shebang Statement

#!/bin/bash

You can find the path to your bash shell with the command:

which bash

Creating Your First Bash Script

Our first script will prompt the user for a directory path and list its contents.

  1. Open your preferred text editor and create a file named run_all.sh. For example, using the vi editor:
vi run_all.sh 
  1. Add the following lines to your file and save it:

#!/bin/bash
echo "Today is " date
echo -e "\nenter the path to directory"
read the_path
echo -e "\n you path has the following files and folders: " ls $the_path

Let’s examine the script line by line:

  1. The shebang (#!/bin/bash) points to the bash shell path.
  2. The echo command displays the current date and time.
  3. Prompts the user to enter a directory path.
  4. The read command stores the user input in the variable the_path.
  5. The ls command lists the files and folders in the path provided by the user.

Executing the Bash Script

To make your script executable, use the following command to add execution permissions:

chmod u+x run_all.sh

This command gives the user execution rights, allowing the script to be run. You can then execute the script with:

sh run_all.sh
bash run_all.sh
./run_all.sh

Bash Scripting Basics

Comments in Bash Scripting

Comments in bash scripting begin with a #. Any line starting with this symbol is considered a comment and is ignored by the interpreter.

Comments are essential for documenting code, aiding both the original author and others in understanding the script’s functionality.


# This is an example comment

# Both of these lines will be ignored by the interpreter

Variables and Data Types in Bash

Variables in Bash allow for the storage and manipulation of data. They can hold numeric values, characters, or strings.

Unlike other programming languages, Bash does not have distinct data types, and variables are assigned and used as follows:

  • Assign a value directly:
    country=Pakistan
  • Assign a value based on command output:
    same_country=$country

To access a variable’s value, prepend it with a dollar sign:

echo $country

Variable Naming Conventions

  • Start with a letter or underscore.
  • Can contain letters, numbers, and underscores.
  • Are case-sensitive.
  • Should not include spaces or special characters.
  • Use descriptive names that reflect their purpose.
  • Avoid using reserved keywords like if, then, else, fi.

Valid: name, count, _var, myVar, MY_VAR

Invalid: 2ndvar, my var, my-var

Input and Output in Bash Scripts

Gathering Input

The read command is used to gather user input and store it in a variable:


#!/bin/bash
echo "Today is " `date`
echo -e "\nenter the path to directory"
read the_path
echo -e "\nyour path has the following files and folders: "
ls $the_path
    

Reading from a file and command line arguments are other methods for input:

  • Reading from a file:
    while read line; do echo $line; done < input.txt
  • Command line arguments:
    echo "Hello, $1!"

Displaying Output

There are several ways to display output from a script:

  • Printing to the terminal:
    echo "Hello, World!"
  • Writing to a file:
    echo "This is some text." > output.txt
  • Appending to a file:
    echo "More text." >> output.txt
  • Redirecting output:
    ls > files.txt

Basic Bash Commands

Here’s a list of fundamental bash commands:

  • cd: Change the current directory.
  • ls: List directory contents.
  • mkdir: Create a new directory.
  • touch: Create a new file.
  • rm: Remove a file or directory.
  • cp: Copy a file or directory.
  • mv: Move or rename a file or directory.
  • echo: Print text to the terminal.
  • cat: Concatenate and display file contents.
  • grep: Search for a pattern in a file.
  • chmod: Change file or directory permissions.
  • sudo: Execute a command with superuser privileges.
  • df: Display disk space usage.
  • history: Show a list of executed commands.
  • ps: Show information about running processes.

Conditional Statements (if/else) in Bash Scripting

Conditional statements are crucial in scripting as they allow for decision-making based on whether a condition is true or false.

Understanding Conditions

Conditions are expressions that evaluate to a boolean value. In bash, you can use if, if-else, if-elif-else, and even nest these to create more complex logic.

Syntax of Bash Conditional Statements


if [[ condition ]]; 
then
    statement
elif [[ condition ]]; then
    statement
else
    do this by default
fi
   

Logical operators such as -a (AND) and -o (OR) can be used to create more meaningful comparisons.

Example

if [ $a -gt 60 -a $b -lt 100 ]
This statement checks if both conditions are true: a is greater than 60 AND b is less than 100.

Example Bash Script

The following script determines if a user-inputted number is positive, negative, or zero:


#!/bin/bash

echo "Please enter a number: "
read num

if [ $num -gt 0 ]; then
    echo "$num is positive"
elif [ $num -lt 0 ]; then
    echo "$num is negative"
else
    echo "$num is zero"
fi
   

The script prompts the user for a number and then uses conditional statements to classify the number.

Looping in Bash

While Loop

A while loop continues to execute as long as the specified condition is true:


#!/bin/bash
i=1
while [[ $i -le 10 ]]; do
    echo "$i"
    (( i += 1 ))
done
This loop iterates 10 times, incrementing i each time.
    

For Loop

A for loop allows you to execute a block of code a specific number of times:


#!/bin/bash

for i in {1..5}; do
    echo $i
done
This loop iterates 5 times. 

Case Statements

Case statements in Bash are used for pattern matching:


case expression in
    pattern1)
        # code to execute if expression matches pattern1
        ;;
    pattern2)
        # code to execute if expression matches pattern2
        ;;
    *)
        # code to execute if none of the patterns match expression
        ;;
esac
    

Each pattern is followed by a block of code to execute if the pattern matches the expression. The double semicolon ; separates each pattern block, and an asterisk * is used as a default case.

Scheduling Scripts with cron

Cron is a Unix utility for time-based job scheduling:


# Cron job example
* * * * * sh /path/to/script.sh

The asterisks represent different units of time (minutes, hours, days, months, weekdays). Here are some examples of cron job scheduling:

Schedule Description Example
0 0 * * * Run a script at midnight every day 0 0 * * * /path/to/script.sh

Debugging and Troubleshooting Bash Scripts

Debugging is an essential skill for scripters. Here are some techniques:

  • Set set -x at the beginning of the script to enable debugging mode.
  • Check the exit code of the last command with $?.
  • Insert echo statements to display variable values.
  • Use set -e to exit the script immediately if a command fails.

For cron jobs, troubleshooting can involve checking log files, such as /var/log/syslog on Ubuntu/Debian systems.

Conclusion

This article covered accessing the terminal, basic bash commands, bash shell, loops, conditionals, cron job scheduling, and troubleshooting techniques.