DEV Community

Cover image for Master Bash Scripting: A Practical Guide for Systems & Automation
Shatakshi
Shatakshi

Posted on

Master Bash Scripting: A Practical Guide for Systems & Automation

Stop running the same 10 commands manually every day. I put together this summary to help you automate your workflow in minutes. So to make such monotonous task more interesting.

what is bash scripting?

A bash script is a file containing a sequence of commands that are executed by the bash program line by line. It allows you to perform a series of actions, such as navigating to a specific directory, creating a folder, and launching a process using the command line.

By saving these commands in a script, you can repeat the same sequence of steps multiple times and execute them by running the script.

Bash scripting is a powerful and versatile tool for automating system tasks, managing system resources, and performing other routine tasks in Unix/Linux systems

Terms like "bash" and "Shell" are used interchangeably. but difference must be understood.
shell is a program that provides command line interface for interacting with the operating system.

a shell or command-line looks like:

shell interface

the shell accepts commands from user and displays the output

In the above output, shatakshi@truamateur is the shell prompt. When a shell is used interactively, it displays a $ when it is waiting for a command from the user.

If the shell is running as root (a user with administrative rights), the prompt is changed to #.
some other shells are, C shell (csh), and Z shell (zsh). Each shell has its own syntax and set of features, but they all share the common purpose of providing a command-line interface for interacting with the operating system.

Some bash commands:

date: display current date
pwd: display the current working directory
echo: Prints a string of text, or value of a variable to the terminal.
cat: View contents of a file

how to create and execute bash scripts

script naming conventions

By naming convention, bash scripts end with .sh. However, bash scripts can run perfectly fine without the sh extension.

Adding the Shebang

Bash scripts start with a shebang. Shebang is a combination of bash # and bang ! followed by the bash shell path. This is the first line of the script. Shebang is simply an absolute path to the bash interpreter.

Below is an example of the shebang statement.
#!/bin/bash

creating your first bash script:

our first script prompts the user to enter a path. in return, its content will be listed.

create a file named run_all.sh using code command. here im using vs code to create, modify and execute the bash script.
move to the directory that you wish to create this script in using cd filename and then:

code run_all.sh

add the following content in the 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
Enter fullscreen mode Exit fullscreen mode
  • Line #1: The shebang (#!/bin/bash) points toward the bash shell path.

  • Line #2: The echo command is displaying the current date and time on the terminal. Note that the date is in backticks.

  • Line #4: We want the user to enter a valid path.

  • Line #5: The read command reads the input and stores it in the variable the_path.

  • Line #8: The ls command takes the variable with the stored path and displays the current files and folders.

executing the bash script:

to make the script executable assign executable rights:

chmod u+x run_all.sh

-chmod is used to change the ownership of file for current user: u
-+x adds the execution rights to the current user. This means that the user who is the owner can now run the script.
-run_all.sh is the file we wish to run.

then we run the script using the following method:

sh run_all.sh

some side notes:
if you are struggling to get correct path when prompted by shell script then you can either enter into the directory that you wish to enter path of and then just enter .
or
you can just drag and drop the folder without entering into the directory.
one thing to note is that you must be in the directory that has run_all.sh script. then only the above points work.

example:

dot-example

drag-drop

another-example

here my l2c folder has the run_all.sh file.

Bash Scripting Basics

comments in bash scripting: we use the # to begin comments in script file

script-comments

Variables and data types in bash:

Variables let you store data. You can use variables to read, access, and manipulate data throughout your script.

There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.

in bash, we can set and use the variable in following ways:

  1. assign value directory
    name=shatakshi

  2. assign a new variable an existing variable value. a $ is needed to use already assigned variable:
    my_name=$name

example:

variable-example

Variable naming conventions:

  1. variable can either begin with a letter(A-Za-z) or an underscore(_)
  2. variable can contain a letter, number or an underscore
  3. variables are case-sensitive
  4. reserved keywords should not be used like if, elif,then etc

input and output in bash scripts

reading input

we read user input using the read command

#!/bin/bash 

echo "What's your name?" 

read entered_name 

echo -e "\nHi $entered_name hope you are having good time learning bash scripting"
Enter fullscreen mode Exit fullscreen mode

output:

var-ex

Command line arguments

we can pass arguments while entering the execute command. the arguments are denoted by $1, $2 and so on.
example:

#!/bin/bash
echo "Hello, $1"
Enter fullscreen mode Exit fullscreen mode

output:

cmd-ex

Displaying output:

  1. print to terminal:
    echo "hii"

  2. write to a file:
    echo "This is some text." > output.txt

  3. append to file:
    echo "More text." >> output.txt

Conditional statements (if/else)

Expressions that produce a boolean result, either true or false, are called conditions. There are several ways to evaluate conditions, including if, if-else, if-elif-else, and nested conditionals.

Syntax:

if [[ condition ]];
then
    statement
elif [[ condition ]]; then
    statement 
else
    do this by default
fi
Enter fullscreen mode Exit fullscreen mode

the keyword fi is used to terminate an if statement.

We can use logical operators such as AND -a and OR -o to make comparisons that have more significance.

if [ $a -gt 60 -a $b -lt 100 ]
Let's see an example of a Bash script that uses if, if-else, and if-elif-else statements to determine 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
Enter fullscreen mode Exit fullscreen mode

looping and branching in bash

while loop:

while loop checks a condition and keeps executing till condition remains true.

in example below, ((i += 1)) is used to increment variable i on each iteration and also checks the condition

#!/bin/bash
i=1
while [[ $i -le 10 ]] ; do
   echo "$i"
  (( i += 1 ))
done
Enter fullscreen mode Exit fullscreen mode

for loop:

just like while loop, just different syntax:

#!/bin/bash

for i in {1..5}
do
    echo $i
done
Enter fullscreen mode Exit fullscreen mode

the expansion starts at number 1 and ends at 5.
the loop will run exactly 5 times.

How to Debug Bash Scripts

Debugging and troubleshooting are essential skills. Bash scripts are also prone to errors and unexpected behavior. In this section, we will discuss some tips and techniques to overcome these challenges.

Set the set -x option

by using set -x command at the beginning of the script, it enables debugging mode, which causes Bash to print each command that it executes to the terminal, preceded by a + sign. This can be helpful in identifying where errors are occurring in your script.

#!/bin/bash

set -x

# Your script goes here
Enter fullscreen mode Exit fullscreen mode

example:

set -x

Check the exit code

When Bash encounters an error, it sets an exit code that indicates the nature of the error. You can check the exit code of the most recent command using the $? variable. A value of 0 indicates success, while any other value indicates an error.

#!/bin/bash

# Your script goes here

if [ $? -ne 0 ]; then
    echo "Error occurred."
fi
Enter fullscreen mode Exit fullscreen mode

example code:

#!/bin/bash

ls /some/folder/that/doesnt/exist

if [ $? -ne 0 ]; then
    echo "Error occurred"

fi
Enter fullscreen mode Exit fullscreen mode

output:

#? example

note: "read" command almost always works. use something like timeout on "read" like:

#!/bin/bash
echo "enter a number"
read -t 3 num

if [$? -ne 0]; then
   echo "error occurred"
fi
Enter fullscreen mode Exit fullscreen mode

output:
timeout read

the timeout here occurs after 3 seconds. dont type anything, and the output is shared.

Use echo statements

echo command is very useful to understand exactly where the problem is happening and what values are being passed to variables.

#!/bin/bash

# Your script goes here

echo "Value of variable x is: $x"

# More code goes here
Enter fullscreen mode Exit fullscreen mode

Use the set -e option

If you want your script to exit immediately when any command in the script fails, you can use the set -e option. This option will cause Bash to exit with an error if any command in the script fails.

#!/bin/bash

set -e

# Your script goes here
Enter fullscreen mode Exit fullscreen mode

set -e example

set -e output

note the difference, as soon as the command read -t 3 num fails the flow stops and exits immediately without reaching the next line of $? variable

Thanks for reading through! i hope this blog has helped in some way or other to better understand the bash scripting in tldr way.
the source of this summary is: Bash Scripting Tutorial

Feedbacks are appreciated. Thanks!
connect here: https://x.com/truamateur
email: shatakshi.gupta85@gmail.com

Top comments (0)