30+ Effective Bash Script Examples You Need to Know

Posted in

30+ Effective Bash Script Examples You Need to Know
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    Bash is a handy tool if you are a developer and wish to experience the power of software development. It has a wide variety of utilities and features for facilitating working with Linux. In this article, I will discuss 50 of the most important examples that you may experience while working with bash scripting. Let’s dive into it! As this is going to be a lengthy article, here is the list of the topics (Bash script examples) covered in this article:

    1. What is Bash?
    2. Creating a shell script file
    3. Displaying your message in the terminal
    4. Taking user input from the terminal
    5. Performing arithmetic operations on variables (Addition and Subtraction)
    6. Performing arithmetic operations on variables (Multiplication and Division)
    7. Single line comments in Bash Scripting
    8. Multi-line comments in Bash Scripting
    9. From scalar to vector: Arrays in Bash
    10. From scalar to vector: Strings in Bash
    11. Conditional statements in Bash Scripting
    12. Performing iteration using for loop
    13. While loop
    14. Check if a number of positive or negative
    15. Check if a number is divisible by 5
    16. Check parity of a number
    17. Find the sum of first ‘ n ’ natural numbers
    18. Sum of digits of an integer
    19. Get largest of three numbers in Bash
    20. Swapping two numbers in Bash
    21. Calculate the area of a rectangle in bash
    22. Calculate quotient and remainder of two numbers
    23. Get the size of the array in Bash
    24. Display length of a string in Bash Script
    25. Concatenation of strings
    26. Add array elements in Bash
    27. Generate factorial of a number
    28. Deleting files in Bash Script
    29. Deleting files after user confirmation
    30. Deleting a directory using Bash Script
    31. Mailing in Bash Script
    32. The Sleep command
    33. Check if you are a root user
    34. Appending content to a file
    35. The ‘Wait’ command
    36. Create a function in Bash Script
    37. Parsing date
    38. Using time command in your bash script
    39. Creating directories
    40. Cleaning log files
    41. Reading the command-line arguments
    42. Function of parameters
    43. Using logical operators in Bash (The AND operator)
    44. Logical OR operator
    45. Slicing the string
    46. Maintain your system using Linux
    47. Check if two string are equal
    48. Extract string using ‘cut’ command
    49. Get the name of the last updated file
    50. Back up the files and directories in your system

    What is Bash?

    Bash is a UNIX (not Linux) shell and command language that is widely used for writing shell scripts in most Linux distributions. Bash was also the default shell in all versions of macOS prior to the 2019 release of macOS Catalina, which changed the default shell to ‘ Z Shell ’ (zsh), although Bash currently remains available as an alternative shell. Bash typically works in a text window where users can write commands and perform tasks, like system administration, automation, and network programming. It’s an acronym for Bourne Again Shell , which is a replacement for Bourne Shell . Writing commands and instructions in a bash script file and allowing automated execution of commands is called bash scripting . The forthcoming portion discusses how you can get started with bash scripting along with the respective commands. Let’s go!

    1. Creating a Shell Script File

    In order to perform bash scripting, you will need to write commands in a shell script file and then run it in your Linux terminal. The most common extension for shell script files is ‘ .sh ’ Let’s create a new file named ‘ test.sh ’ in the present working directory and write our commands in this file. The new file can be created using the ‘ touch ’ command in Linux. After creating the file, you can list the directories and files in the present working directory to verify that the file was created.

    To run the script file, you can run the following command in your terminal:

     
    $ bash test.sh

    This will automatically execute all the commands in your test.sh file one by one.

    2. Displaying your message in the terminal

    In many cases, you may need to display some message either for the user or for debugging purposes. The ‘ echo ’ command will help you here. It displays a message or any variable as standard output in your terminal. The ‘ #!/bin/bash’ character sequence at the top of the file is called Shebang in UNIX-like systems and executes the file using the bash shell. Write the following code in test.sh with your favorite text editor and run the bash command as shown in the image:

    #!/bin/bash
    echo "Hello there! Welcome to the Linux tutorials"

    Using ‘ -e ‘ after the ‘ echo ‘ command acts as an interpretation of escaped characters that are present with backlashes. For instance,‘ \n ’ in a string acts as a line breaker and ‘ \t ’ is used to insert tabs at its place in the standard output.

    #!/bin/bash
    echo -e "Hello there!\n Welcome to the Linux tutorials"

    You can also create custom variables in your script and display their values. For this, you will need to add ‘ $ ‘ before the variable, otherwise, it will be treated as a standard string . We will be using integer types of variables in this article for your convenience. You can also display environment variables and examine them depending on your use case. Below is the script to assign a variable with some value and displaying it in the terminal.

     
    #!/bin/bash
    var=2
    echo $var

    3. Taking user input from the terminal

    The user input can be accepted using the ‘ read ’ command in the Bash script. This command takes input from the user and stores it in a variable. You don’t need to declare the variable before reading it .

     
    #!/bin/bash
    echo "Enter your value"
    read var 
    
    echo "You entered $var"

    You can also take standard input for multiple variables using the ‘ read ’ command by separating them with space/s. An illustration for this is:

     
    #!/bin/bash
    echo "Enter your values"
    read var1 var2
    echo "You entered $var1 and $var2"

    4. Performing arithmetic operations on variables (Addition and Subtraction)

    Bash provides you with arithmetic operators for doing basic math in your script. The operators can be either unary or binary . Let’s write a script to demonstrate the addition and subtraction of 2 variables and display the result in your terminal:

    #!/bin/bash
    
    echo "Enter your values"
    read a b
    sum=$((a+b))
    diff=$((a-b))
    echo "Sum is $sum and difference is $diff"

    5. Performing arithmetic operations on variables (Multiplication and Division)

    Let’s write another script to display the product and quotient when integers are multiplied and divided respectively:

    #!/bin/bash
    
    num1=10
    num2=20
    
    mul=$((num1*num2))
    div=$((num2/num1))
    
    echo "Product is $mul and quotient is $div"

    6. Single line comments in Bash Scripting

    Comments are a useful way to recall your logic later. They are also helpful while working with a team. Writing comments is also considered a good practice, particularly for lengthy codes. Single line comments can be added using ‘ # .

    #!/bin /bash
    # assign a value to a variable
    
    a=50
    #thereafter print the variable
    echo $a

    7. Multi-line comments in Bash Scripting

    You can write multi-line comments in Bash script by the following method. However, this is not recommended due to potential bug sources :

    : '
    This is my comment 
    '

    8. From scalar to vector: Arrays in Bash

    Consider a scenario where you may need to store a large number of variables together for performing operations on them. Arrays come to rescue you here. You can store hundreds of values in a single data structure and access them using indexing . The indexing can be performed using the following syntax:

    ${array[index]}

    By default, the array indices start from 0 and go up to n-1 , where n is the size of the array. One method of defining the array and then printing one of its elements is demonstrated in the following script:

     
    #!/bin/bash
    arr=(1 4 5)
    val=${arr[0]}
    echo "Element at index 0 is $val"

    9. From scalar to vector: Strings in Bash

    Strings are sequences of characters that store data in contiguous blocks of memory. Strings are sort of arrays that contain characters as their elements. Let’s create a string in Bash and print its value in the terminal:

    #!/bin/bash
    VAR1='Hello learner'
    echo  $VAR1

    10. Conditional statements in Bash scripting

    It’s quite common that you may need to execute a set of commands under some condition only. This is handled by conditional statements in Bash. The syntax for conditional execution of commands is:

    if [ condition ]
    then
       #do this
    else
       #do this
    fi

    Take proper care with spaces while writing the code for conditional statements in Bash . Below is an illustration on how to compare 2 numbers using conditional statements:

    #!/bin/bash
    a=100
    b=20
    if [ $a == $b ]             #comparing a and b
    then 
         echo "$a is equal to $b"
    else
         echo "$a is not equal to $b"
    fi

    11. Performing iteration using for loop

    Executing the same kind of command multiple times is quite common practice in your scripts. You can write the same command around 5 to 6 times but writing the same thing more than 100 or 1000 times is both a tedious task and is not considered good practice in coding. The for loop is one of the alternatives you can go for this. This allows you to initialize a variable with some value and increment/decrement it until some condition is satisfied. An example of using a loop is mentioned below. The script starts a variable from 0, which goes up to 5. The ‘-n’ option tells the script not to break the line after printing the standard output:

    #!/bin/bash
    
    for ((itr=0; itr<=5; itr++)) 
    do
    echo -n "$itr "
    done

    12. While loop

    While loop is similar to for loop in terms of working. It runs until some condition is satisfied:

    #!/bin/bash
    n=0
    while [ $n -le 5 ]
    do
      echo $n
      ((n++))
    done

    13. Check if a number is positive or negative?

    The task can be done using conditional statements in Bash scripting as demonstrated below:

    #!/bin/bash
    
    echo "Enter a Number"
    read num
    
    if [ $num -lt 0 ]
    then
        echo "Negative"
    elif [ $num -gt 0 ]
    then
        echo "Positive"
    else
        echo "Neither Positive Nor Negative"
    fi

    14. Check if a number is divisible by 5

    As an example of a modulo operator, let’s see how we can check if a number is divisible by 5 using the following script:

    #!/bin/bash
    
    read -p "Enter a number: " num
    if [ $((num%5)) -eq 0 ]
    then
      echo "Number is divisible"
    else
      echo "Number is not divisible"
    fi

    15. Check parity of a number

    Parity refers to checking if a number is odd or even. We can use the modulo operator to check parity. If a number is divisible by 2, it is an even number, otherwise, it is an odd number.

    #!/bin/bash
    
    read -p "Enter a number: " num
    if [ $((num%2)) -eq 0 ]
    then
      echo "Number is even."
    else
      echo "Number is odd."
    fi

    16. Find the sum of first ‘ n ’ natural numbers

    We will discuss this approach using a while loop here. We will iterate from 1 to ‘ n’ (where ‘n’ is some natural number) and keep updating the sum by adding the current value to it:

    #!/bin/bash
    
    N=3
    i=1
    sum=0
    while [ $i -le $N ]
    do
      sum=$((sum + i)) #sum+=num
      i=$((i + 1))
    done
    echo “Sum is $sum”

    If you are a math geek, you should have definitely thought of a more efficient approach for this problem. Share in the comments section below!

    17. Sum of digits of an integer

    You can find the sum of digits of a natural number by using a simple algorithm in Bash. Get the last digit of the number by modulo operating the number with 10. Divide the number by 10 to skip this last digit and repeat the same procedure. Keep adding the last digit you obtain in every iteration to your sum.

    #!/bin/bash
    
    echo "Enter the number"
    
    num=12
    sum=0
    
    while [ $num -gt 0 ]
    do
        rem=$((num % 10))    #It will get last digit
        sum=$((sum + rem))   #Add each digit to sum
        num=$((num / 10))    #divide the number by 10.
    done
    
    echo “Sum of digits is $sum”

    18. Get largest of 3 numbers in Bash

    The task can be done using simple conditional statements. The script to get the largest of 3 numbers is written below: Note : There are more approaches to solve this problem. You should definitely brainstorm and think of some other approach.

    #!/bin/bash
    
    echo "Enter number 1"
    read num1
    echo "Enter number 2"
    read num2
    echo "Enter number 3"
    read num3
    
    if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]
    then
        echo $num1
    elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]
    then
        echo $num2
    else
        echo $num3
    fi

    19. Swapping two numbers in Bash

    The 2 numbers can be swapped using a simple algorithm in Bash. For this, we will use a third variable for swapping.

    #!/bin/bash
    
    a=12
    b=24
    temp=$a #place the value in a temp variable for using it later
    a=$b
    b=$temp
    echo "After Swapping"
    echo "First number: $a"
    echo "Second number: $b"

    Of course, there can be more efficient approaches to perform this task. Think of it yourself! That’s what programmers have to do!

    20. Calculate the area of a rectangle in bash

    For this, you just need to multiply the length and breadth of the rectangle.

    #!/bin/bash
    
    l=10
    b=2
    area=$[$l*$b]
    echo "The area of the rectangle is $area"

    21. Calculate quotient and remainder of the two numbers

    The remainder of the two numbers is the number left when the dividend is divided by the divisor. The quotient simply tells with what value, the divisor must be multiplied to get the dividend (if we ignore the remainder part). Here’s the script to find the quotient and remainder of two numbers :

    #!/bin/bash
    
    dividend=15
    divisor=2
    quotient=$((dividend/divisor))
    rem=$((dividend%divisor))
    echo "Quotient is: $quotient"
    echo "Remainder is: $rem"

    22. Get the size of the array in Bash

    You can get the number of elements present in the array by using the following script:

    #!/bin/bash
    
    $ my_array=(1 3 4)
    $ echo "The array contains ${#my_array[@]} elements"

    23. Display length of a string in Bash String

    Bash scripting provides you the facility to find the length of a given string, which may be helpful in various debugging or general tasks.

    #!/bin/bash
    sentence="Welcome"
    echo "Length of string is: ${#sentence}"

    24. Concatenation of strings

    It’s an effortless task to concatenate multiple strings in Bash script. Concatenation may be helpful while working with directory or file paths in Linux.

    #!/bin/bash
    
    string1="Bash "
    string2="Scripting"
    string=$string1$string2
    echo "$string is interesting."

    25. Add array elements in Bash

    To find the summation of elements of an array, you simply need to iterate through the indices of the array and keep adding the current value to your sum. Let’s see the code to this logic!

    #!/bin/bash
    arr=(1 2 3 4 5)
    summation=0
    
    for element in ${arr[@]}
    do
        summation=`expr $summation + $element`
    done
    
    echo $summation

    26. Generate factorial of a number

    Factorial of a number recursively calculates product from 1 to n, where n is some arbitrary integer. It’s useful in mathematical domains like number theory and combinatorics . Below is the Bash script to calculate the factorial of a number:

    #!/bin/bash
    echo -n "Enter a number: "
    read n
    fact=1
    while [ $n -gt 1 ]
    do
     fact=$((fact *  n))
     n=$((n - 1))
    done
    echo $fact

    27. Deleting files in Bash Script

    Deleting files is quite a common task while operating your PC. This can be done by using ‘ rm’ Linux.:

    #!/bin/bash
    
    echo -n "Enter the filename"
    read name
    rm $name
    echo "File has been deleted"

    As you can see above, after running the script, the file test.txt is not present in the present working directory.

    28. Deleting files after user confirmation

    Using the ‘-i’ option with ‘rm’ takes the user confirmation before performing a deletion operation. It’s a good practice to get user confirmation before doing deletion and similar operations to avoid accidental deletion.

    #!/bin/bash
    
    echo -n "Enter the filename"
    read name
    rm -i $name
    echo "File has been deleted

    29. Deleting a directory using Bash script

    Many times, you may need to delete the entire directory. Let’s write a script to perform this task:

    #!/bin/bash
    
    echo "Enter the directory name"
    read name
    rm -rf $name
    echo "Directory has been deleted

    30. Mailing in Bash Script

    One of the best features of bash script is that you can send emails to people using it. This is usually helpful when you need to send mails to hundreds of users. You need to enable SMTP in your OS for sending mails using this script . Let’s see the script to send mail to a person:

    #!/bin/bash
    
    recipient="maazbinasad29@gmail.com"
    subject="Hello from anonymous"
    message="Welcome to the era of bash scripting"
    `mail -s $subject $recipient <<< $message`

    31. The Sleep command

    You can also pause your script for some time and resume it later using Bash Scripting. It can be helpful while performing system-level jobs. The below script pauses for ‘ $t’ seconds and resumes executing the commands:

    #!/bin/bash
    
    echo "Enter number of seconds to wait"
    read t
    sleep $t
    echo "Resuming after $t seconds!"

    32. Check if you are a root user

    The root user has all the privileges in Linux distributions . For creating new users as well, you need to be a root user of Linux. To check if you are a root user, the following script will be helpful:

    #!/bin/bash
    
    ROOT_UID=0
    
    if [ "$UID" -eq "$ROOT_UID" ]
    then
    echo "Great! You are a root user"
    else
    echo "You are not the root user"
    fi

    33. Appending content to a file

    Appending the content means you are inserting the data at the end of an existing file. This can be performed by using the ‘>>’ operator in Bash Script. Let’s see how to do this using a simple example:

    #!/bin/bash
    
    echo "Before appending"
    cat test.txt
    
    echo "Added text">> test.txt
    echo "After appending"
    cat test.txt

    The above script has added the content at the end of ‘test.txt’ . The ‘cat’ command is used to read the file sequentially and write the standard output.

    34. The ‘Wait’ command

    It’s a built-in command in Linux that waits for some running process to complete. It takes the process ID and waits until this particular process is completed.

    #!/bin/bash
    echo "Wait command" &
    process_id=$!
    wait $process_id
    echo "Exited with status $?"

    35. Create a function in Bash Script

    Functions are a great way to follow the DRY (Do not repeat yourself) principle of software development. Instead of writing the same block of code, again and again, you could simply create a function to perform that task and call it whenever you need that block of code. It’s a good practice to include functions in your code as it makes the debugging easier and the code better in readability. Here’s an example:

    #!/bin/bash
    
    function Func()
    {
    echo 'Function called'
    }
    
    Func    #calling the function

    36. Parsing date

    You can also parse the current date and time in Linux using the following set of commands:

    #!/bin/bash
    date=`date`
    echo "Current Date is: $date"

    37. Using time command in your bash script

    The ‘time’ command prints verbose timing statistics for executing a command:

    #!/bin/bash
    time

    38. Creating directories

    The directory is a set of files and sub-directories in an OS. We can create a new directory in the current working directory by using the mkdir command in Linux . The below script checks if the directory already exists in the present working directory. If not, it creates one with the name entered by the user.

    #!/bin/bash
    echo -n "Enter directory name"
    read dir
    if [ -d "$dir" ]
    then
    echo "Directory exists"
    else
    `mkdir $dir`
    echo "Directory created"
    fi

    39. Cleaning log files

    Log files are records maintained for the administrator that keeps messages related to kernels, applications and servers. We can clean the log files using the following script: Note : You need root privileges to run this script.

     
    #!/bin/bash
    
    LOG_DIR=/var/log
    cd $LOG_DIR
    
    cat /dev/null > messages
    cat /dev/null > wtmp

    40. Reading the command-line arguments

    Like any other programming language, Bash also provides a way to read command-line arguments. These are arguments passed to your program during program execution. They are helpful to control the execution of your program from the outside. Variables ‘$1’ and ‘$2’ are used to read the first two command-line arguments. Below is the script to write first and second command-line arguments that are passed during the file execution: #!/bin/bash

    echo "Number of arguments : $#"
    echo "Argument 1= $1"
    echo "Argument 2= $2"

    41. Function of parameters

    You can also call a function by passing a few arguments to it. Obviously, you may need custom values for performing some task most of the time using functions. This can be done by giving parameters to the function as shown below:

    #!/bin/bash
    
    Square_Area() {
    area=$(($1 * $1))
    echo "Area of square is : $area"
    }
    
    Square_Area 10

    42. Using logical operators in Bash (The AND operator)

    Logical operators are used to combine one or more conditions and result in a single output. For instance, a logical AND operator can be used to check if an integer is both even and less than 5. An illustration for this is:

    #!/bin/bash
    
    echo -n "Enter some integer:"
    read num
    
    if [[ ( $num -lt 5 ) && ( $num%2 -eq 0 ) ]]; then
    echo "Even and less than 5"
    else
    echo "Not satisfied above condition"
    fi

    43. Logical OR operator

    The names of logical operators are quite self-explanatory. The OR operator results true if either of the two conditions is true. See the example below:

    #!/bin/bash
    
    echo -n "Enter any number:"
    read n
    
    if [[ ( $n -eq 10 || $n -eq 20 ) ]]
    then
    echo "YES"
    else
    echo "NO"
    fi

    The above code prints “YES” if the number is either 10 or 20. Otherwise, it prints “NO.”

    44. Slicing the string

    Slicing a string refers to extracting a substring from a given string. Please note that the string is a substring of itself. Let’s extract a substring from a given string in a Bash script:

    #!/bin/bash
    
    Str="Hey! Welcome to Bash script tutorials"
    subStr=${Str:0:20}
    echo $subStr

    45. Maintain your system using Linux

    Instead of manually writing commands every time to maintain and upgrade the system, you can just write the below script to execute the required commands for upgrading the system. After all, it's the era of automation!

    #!/bin/bash
    
    echo -e "\n$(date "+%d-%m-%Y --- %T") --- Starting\n"
    
    apt-get update
    apt-get -y upgrade
    
    apt-get -y autoremove
    apt-get autoclean
    
    echo -e "\n$(date "+%T") \t Done!"

    46. Check if two strings are equal

    Equal strings have the same length and exactly the same characters at each index. The following script checks if the two strings are equal or not using simple conditional logic:

    #!/bin/bash
    
    #declare strings
    S1="Hello"
    S2="Learner"
    if [ $S1 = $S2 ]; then
     echo "Strings are equal"
    else
     echo "Strings are not equal"
    fi

    47. Extract string using the ‘cut’ command

    We can get a portion of the string using the ‘cut’ command in Linux. The script to perform this operation is:

    #!/bin/bash
    
    Str="Learn Bash Commands from this tutorial"
    #subStr=${Str:0:20}
    
    sub=$(echo $Str| cut -d ' ' -f 1-3)
    echo $sub

    48. Get the name of the last updated file

    In certain tasks, you may need to get the name of the file that was last updated or created in your system. This task can be done using the ‘awk’ command.

    #!/bin/bash
    
    ls -lrt | grep ^- | awk 'END{print $NF}'

    49. Back up the files and directories in your system

    A handy way to backup the files and folders that were updated in the last 24 hours is to use the following script in Linux:

    #!/bin/bash
    
    BACKUPFILE=backup-$(date +%m-%d-%Y)
    archive=${1:-$BACKUPFILE}
    
    find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar"
    echo "$PWD backed up in archive file \"$archive.tar.gz\"."
    exit 0

    Conclusion

    These were the 50 best examples of performing Bash scripting in your Linux distributions. Bash provides you with many other utilities and statements that can be used to efficiently automate the execution process of the commands. We also saw how bash scripting is a handy way to perform the administration and maintenance of your system.

    People are also reading:

    Leave a Comment on this Post

    0 Comments