DEV Community

Cover image for Bash Shell Scripting: The Basics
Frank
Frank

Posted on

Bash Shell Scripting: The Basics

We can't remember all of the hundreds of commands available to command line users. The actual strength of the computer is its capacity to perform the job for us, and we leverage the power of the shell to automate tasks by writing shell scripts.

What are Shell Scripts?
In it's simplest form, a shell script is a file containing a series of commands that the shell reads and executes as if they were entered directly on the command line. The shell serves as both a powerful command line interface to the system and a scripting language interpreter. As we will see, most of what can be done on the command line can also be done in scripts.

We have covered some shell features, but we have focused on those most typically used directly on the command line. The shell also provides a collection of features that are usually (but not always) used when developing programs. Scripts unlock the potential of our Linux computer, so let's have fun!


  1. Writing Our First Script and Getting It to Work
  2. Working with Variables
  3. Loops and Conditionals

Writing Our First Script and Getting It to Work

To create/write a shell script, follow these steps:

  1. Create the script

  2. Allow the shell to execute it

  3. Place it somewhere accessible to the shell

Creating Your First Script

We use a text editor to develop shell scripts. A text editor is a program similar to a word processor that reads and writes ASCII text files. There are numerous text editors available for Linux systems, both command-line and GUI-based. These are a few common ones:

Name Description Interface
vi, vim Vi is notorious for its confusing user interface. On the plus side, vi is powerful, light, and speedy. Learning vi is considered a Unix rite of passage because it is widely available on Unix-like platforms. CLI
Emacs Emacs, created by Richard Stallman, is the true behemoth of text editors. It has (or can be made to have) every feature that has ever been imagined for a text editor. It's worth noting that supporters of both vi and Emacs are at odds about which is superior. CLI
nano Nano is a freeware clone of the text editor included with the Pine email application. Nano is simple to use, but has less features than vim and emacs. Nano is recommended for first-time users that require a command-line editor. CLI
gedit gedit is an editor that comes with the GNOME desktop interface. It is straightforward to use and has enough features to be a suitable beginner's editor. Graphical
kwrite kwrite, the "powerful editor" which comes with KDE, offers syntax highlighting, which is useful for programmers and scripts writers. Graphical

Writing a Bash script is like writing down a list of commands that you want the computer to execute. Here's how you can create your first script:

#!/bin/bash
# This is my First Script
echo "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

The first line of the script is essential. It is called a shebang it's a particular construct that tells the system which program will be used to understand the script.
Coming down we have a comment. Whatever follows a "#" symbol is ignored by bash. Comments are very vital as our scripts becomes bigger and complicated.
Save this in a file named hello.sh, make it executable using chmod +x hello.sh, and run it with ./hello.sh.
We should see "Hello, World!" displayed


Working with Variables

Working with variables in Bash is a vital skill that enables you to store and alter data within scripts. Variables serve as placeholders for values, such as strings or numbers, that can be utilized repeatedly throughout your script. Let's look at how you can interact with variables in Bash.

1. Defining Variables

In Bash, you define a variable by simply assigning it a value. There is no need to declare the type of the variable, as Bash is dynamically typed.

Syntax:

variable_name=value
Enter fullscreen mode Exit fullscreen mode
  • No spaces: There should be no spaces between the variable name, the equal sign =, and the value.
  • Case sensitivity: Variable names are case-sensitive (name and Name are different variables).

Example:

#!/bin/bash
name="Frank"
age=30
Enter fullscreen mode Exit fullscreen mode

2. Accessing Variables

To access the value stored in a variable, you prefix the variable name with a dollar sign $.

Syntax:

echo $variable_name
Enter fullscreen mode Exit fullscreen mode

Example:

#!/bin/bash
name="Frank"
echo "Hello, $name!"
Enter fullscreen mode Exit fullscreen mode

This script will output:

Hello, Frank!
Enter fullscreen mode Exit fullscreen mode

3. Modifying Variables

You can change the value of a variable by assigning a new value to it.

Example:

#!/bin/bash
count=5
echo "Initial count: $count"

count=10
echo "Updated count: $count"
Enter fullscreen mode Exit fullscreen mode

Output:

Initial count: 5
Updated count: 10
Enter fullscreen mode Exit fullscreen mode

4. Using Variables in Strings

You can embed variables directly within strings using double quotes.

Example:

#!/bin/bash
tool="Git Bash"
echo "I am using $tool to write scripts."
Enter fullscreen mode Exit fullscreen mode

This will output:

I am using Git Bash to write scripts.
Enter fullscreen mode Exit fullscreen mode

5. Working with Numbers

Bash treats variables as strings by default, but you can perform arithmetic operations using the (( )) syntax.

Example:

#!/bin/bash
a=5
b=3
sum=$((a + b))
echo "The sum of $a and $b is $sum."
Enter fullscreen mode Exit fullscreen mode

This will output:

The sum of 5 and 3 is 8.
Enter fullscreen mode Exit fullscreen mode

6. Using Command Output as a Variable

You can assign the output of a command to a variable using backticks `command` or the $(command) syntax.

Example:

#!/bin/bash
current_directory=$(pwd)
echo "You are in $current_directory."
Enter fullscreen mode Exit fullscreen mode

This will output something like:

You are in /home/frank/Desktop.
Enter fullscreen mode Exit fullscreen mode

7. Environment Variables

Environment variables are special variables that are available system-wide and can be used by any process. Examples include PATH, HOME, and USER.

Example:

#!/bin/bash
echo "Your home directory is $HOME."
echo "Your username is $USER."
Enter fullscreen mode Exit fullscreen mode

8. Exporting Variables

If you want a variable to be available to other scripts or programs started from your current script, you can export it.

Syntax:

export variable_name=value
Enter fullscreen mode Exit fullscreen mode

Example:

#!/bin/bash
export my_var="Hello World"
Enter fullscreen mode Exit fullscreen mode

9. Unsetting Variables

If you need to remove a variable or unset its value, you can use the unset command.

Example:

#!/bin/bash
name="Frank"
unset name
echo "Name is $name"
Enter fullscreen mode Exit fullscreen mode

Since name has been unset, the output will be empty.

10. Special Variables

Bash also provides special variables that hold specific information, such as:

  • $0: The name of the script.
  • $1, $2, etc.: Positional parameters (arguments passed to the script).
  • $#: The number of positional parameters.
  • $?: The exit status of the last command.
  • $$: The process ID of the current shell.

Example:

#!/bin/bash
echo "The name of this script is $0"
echo "The first argument passed is $1"
Enter fullscreen mode Exit fullscreen mode

Loops and Conditionals

Loops and conditionals are fundamental constructs in Bash scripting that allow you to control the flow of your script.

Numeric Comparison Operators:

-lt: Less than (a -lt b checks if a is less than b).
-le: Less than or equal to (a -le b checks if a is less than or equal to b).
-gt: Greater than (a -gt b checks if a is greater than b)
-ge: Greater than or equal to (a -ge b checks if a is greater than or equal to b).
-eq: Equal to (a -eq b checks if a is equal to b).
-ne: Not equal to (a -ne b checks if a is not equal to b).

Conditionals

Conditionals let you execute specific blocks of code based on certain conditions. The most common conditional statements in Bash are if, elif, else, and case.

if Statement

The if statement checks a condition and, if true, executes the corresponding block of code.

Syntax:

if [ condition ]; then
    # Code to execute if the condition is true
fi
Enter fullscreen mode Exit fullscreen mode

Example:

#!/bin/bash
number=10

if [ $number -gt 5 ]; then
    echo "The number is greater than 5"
fi
Enter fullscreen mode Exit fullscreen mode

This script will output:

The number is greater than 5
Enter fullscreen mode Exit fullscreen mode

fi

fi is a keyword used to close an if statement in Bash. In Bash, an if block begins with if and must end with fi (which is simply if spelled backward).

if-else Statement

The if-else statement allows you to execute one block of code if the condition is true, and another block if it's false.

Syntax:

if [ condition ]; then
    # Code to execute if the condition is true
else
    # Code to execute if the condition is false
fi
Enter fullscreen mode Exit fullscreen mode

Example:

#!/bin/bash
number=3

if [ $number -gt 5 ]; then
    echo "The number is greater than 5"
else
    echo "The number is 5 or less"
fi
Enter fullscreen mode Exit fullscreen mode

This script will output:

The number is 5 or less
Enter fullscreen mode Exit fullscreen mode

elif Statement

The elif statement stands for "else if" and lets you check multiple conditions.

Syntax:

if [ condition1 ]; then
    # Code to execute if condition1 is true
elif [ condition2 ]; then
    # Code to execute if condition2 is true
else
    # Code to execute if none of the above conditions are true
fi
Enter fullscreen mode Exit fullscreen mode

Example:

#!/bin/bash
number=5

if [ $number -gt 5 ]; then
    echo "The number is greater than 5"
elif [ $number -eq 5 ]; then
    echo "The number is exactly 5"
else
    echo "The number is less than 5"
fi
Enter fullscreen mode Exit fullscreen mode

This script will output:

The number is exactly 5
Enter fullscreen mode Exit fullscreen mode

Loops

Loops allow you to execute a block of code repeatedly. The most common loops in Bash are for, while, and until.

for Loop

The for loop iterates over a list of items, executing the block of code for each item.

Syntax:

for item in list; do
    # Code to execute for each item
done
Enter fullscreen mode Exit fullscreen mode

Example:

#!/bin/bash
for i in 1 2 3 4 5; do
    echo "Number: $i"
done
Enter fullscreen mode Exit fullscreen mode

This script will output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Enter fullscreen mode Exit fullscreen mode

while Loop

The while loop executes a block of code as long as a specified condition is true.

Syntax:

while [ condition ]; do
    # Code to execute as long as the condition is true
done
Enter fullscreen mode Exit fullscreen mode

Example:

#!/bin/bash
count=1

while [ $count -le 5 ]; do
    echo "Count: $count"
    count=$((count + 1))
done
Enter fullscreen mode Exit fullscreen mode

This script will output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Enter fullscreen mode Exit fullscreen mode

until Loop

The until loop is similar to the while loop, but it executes the block of code until a specified condition becomes true.

Syntax:

until [ condition ]; do
    # Code to execute until the condition becomes true
done
Enter fullscreen mode Exit fullscreen mode

Example:

#!/bin/bash
count=1

until [ $count -gt 5 ]; do
    echo "Count: $count"
    count=$((count + 1))
done
Enter fullscreen mode Exit fullscreen mode

This script will output the same as the while loop above.

  • Conditionals (if, else, elif) are used to execute code based on whether a condition is true or false.

  • Loops (for, while, until) are used to repeat a block of code multiple times.


You’ve made it to the end and gotten smarter by learning about Bash Shell Scripting. Now, try practicing what you’ve learned. Good luck!

If you enjoyed this journey and would like to show your support, here’s how you can:

Follow me on Medium for more insightful content.

Connect with me on X, LinkedIn, and GitHub, where I consistently share valuable programming resources for free.

Top comments (2)

Collapse
 
rauldipeas profile image
Raul Dipeas

Maybe You can share better practices to the scripts on the next post, it will be great!

Collapse
 
hanzla-mirza profile image
Mirza Hanzla

👍👍👍👍👍👍👍👍