Bash Scripting in Linux

Posted in

Bash Scripting in Linux
maazbinasad

Maaz Bin Asad
Last updated on December 5, 2024

    Kernel and Shell are the two main elements of an operating system. A kernel is the operating system's brain, and it is in charge of everything in the system. Shell is an exterior wrap that protects the kernel from direct user interference.

    What is Shell?

    Shell is a one-of-a-kind program that gives the user a way to communicate with the kernel by taking human-readable commands and converting them to kernel-friendly code. In a Linux OS, Shell will take user input in the form of instructions, process it, and then show the results. In Linux, you can use Terminal to get to Shell.

    Predominantly, shells can be categorized as Command-Line shells or GUI-based Shells. A user can use command-line interfaces to enter a shell. To get user input in the form of human-readable commands and view output in the same command-line interface, we have several applications, like terminals in Linux distributions or Mac, to execute instructions one by one.

    Similarly, we have Command Prompts in Windows. The graphical shell gives users an interface (GUI) from which they can communicate and execute tasks such as manipulating files, permissions, etc. Windows OS and Debian are excellent examples of GUI Shell (Desktop) environments in which a user does not need to type commands for any task. Even then, any operation is preceded by a shell order that is executed to carry out the action.

    Bash Shell and Scripting

    Most Linux distributions now use BASH (Bourne Again Shell) as their default command-line interpreter. It's an improved version of the Bourne shell from before. To execute day-to-day activities as a Linux server administrator, it’s necessary that you have an outstanding understanding of the commands that are used in the BASH shell.

    Even then, you will be required to perform complicated or routine functions that require the execution of a set of commands in a specific order. A shell will also accept instructions from a file as input, so we can save time by writing these commands in a file and then executing them in the shell. They are referred to as Shell Scripts.

    Advantages and Disadvantages of Bash Scripting

    There are some benefits of using the bash script. It saves time and effort by automating routine tasks. You can build your own utility or power tool. They are portable, which means you can run them on other Linux systems without changing them. It uses the same collection of syntax as a normal terminal, so there is no need to learn something new. With a little assistance, you can easily write a bash script. It will provide remote debugging when tasks are running, which is useful in the event of an error or problem.

    In comparison to these, bash scripts may also have drawbacks. They are vulnerable to mistakes; a single blunder will disrupt the program's flow and cause damage. They have a sluggish rate of execution. Unlike other programming languages, they have very simple data structures. They are not built for executing complex tasks.

    In this comprehensive guide, we will walk you through a basic introduction to bash scripting with a handful of practical examples that will help you to get started with bash scripting. Also, please note although it’s not necessary, however, previous experience with any programming language might help you to understand the syntax and concepts better.

    Getting Started

    First, we will create a simple text file with the shell (.sh) extension. Then, inside the shell file, we will include a command to be executed. Let’s say we want to list all the files in the current directory when we execute the bash script.

    So, we will just include the “ls” command inside the script.

    Bash Script After that, we will execute the bash script using the following command.

    $ bash sample.sh

    Bash Script 2 You can see that all the files and directories have been listed on the execution of the script.

    Creating a Hello World Script

    Let’s create a script called “helloworld.sh” which will simply print a Hello World message to the shell. Please note that we can include the command “#!/bin/sh” which represents the starting of a bash script.

    #!/bin/bash
    echo "Hello World"

    Now, we can run the script using the following command.

    $ bash helloworld.sh

    Creating a Hello World Script

    You can see that the message has been printed successfully.

    Echo Command with Bash Scripts

    The echo command can be used to print text output to the console. The syntax is -

    $ echo [options] [arguments/commands]

    We can use the -n option to suppress the new line trails. The -e option can be used to interpret those characters that are back-slashed. Let’s use the following commands inside a new bash script.

    #!/bin/bash
    echo "Hello and Welcome"
    echo -n "This is a Linux Tutorials\n"
    echo -e "\nBye  \t Bye \t Everyone"

    Echo Command with Bash Scripts

    Comments in Bash Scripts

    Comments inside bash scripts can be denoted by a hash symbol. We can use : ‘<text to comment>’ for multiline comments. See the script below.

    #!/bin/bash
    : '
    Lets print the product of 2 and 8
    '
    ((prod=2*8))
    # The product is
    echo "Product is $prod"

    Comments in Bash Scripts

    Variables in Bash Scripts

    We can use variables to store data temporarily. There are three categories of variables - Environment, Special, and user-defined. There are special variables such as $USER (print the current user), $SECONDS (seconds since when the CLI has been running), $@ (parameters that have been sent to script), etc., that represent preset variables. You can check the environment variables list using the following command -

    $ env | less

    Variables in Bash Scripts You can define your own variables inside the script.

    #!/bin/bash
    message=Welcome
    echo $message

    Variables in Bash Scripts - 2

    User Input

    You can use the read command to get input from users.

    #!/bin/bash
    read message
    echo $message

    User Input

    Loops in Bash Scripting

    We can use loops such as for and while to execute the same code snippet repeatedly. Check the below script that uses a while loop to print numbers from 1 to 10.

    #!/bin/bash
    count=1
    while [ $count -le 10]
    do
    echo “Current Number: $count”
    ((count++))
    done

    The above program set’s a user-defined variable called count and initializes it to 1. We have used a while loop with the condition that it will terminate the loop if the value of the count becomes greater than 10. In each iteration, we print the value stored inside the count variable and increment it by 1. Loops in Bash Scripting Let’s try to perform the same operation using a for loop.

    #!/bin/bash
    flag=1
    for (( flag=1; flag<=10; flag++ ))
    do
        echo "Current Value is: $flag"
    done

    Loops in Bash Scripting - 2

    Conditional Statements in Bash Scripts

    Let’s use an if-elif-else branching to execute a simple program.

    #!/bin/bash
    echo -n "Please enter a number: "
    read number
    if [[ $number -gt 30 ]]
    then
      echo "The Number is greater than 30."
    elif [[ $number -eq 30 ]]
    then
      echo "The Number is equal to 30."
    else
      echo "The Number is less than 30."
    fi

    Here, we will read an input number from the user and check if it is greater than, less than, or equal to 30 and print messages accordingly. Conditional Statements in Bash Scripts

    Functions in Bash Scripts

    You can use functions, just like in other languages, to reuse the same block of code repeatedly. Let’s create a product function that will take two input variables and print the product.

    #!/bin/bash
    function product()
    {
      echo -n "Please enter the first value: "
      read first
      echo -n "Please enter the second value: "
      read second
      echo "The Product is: $(( first*second ))"
    }
    product

    Functions in Bash Scripts

    Wrapping Up!

    Shell scripts in Linux can be really useful. Complex activities, when properly executed, will greatly improve your effectiveness while still assisting you in quickly troubleshooting problems. Furthermore, its scalability is unrestricted. If you're a new Linux user, we strongly advise you to learn how to use bash scripts. You can manipulate files, manage permissions, send emails, and perform tons of similar tasks using simple bash scripts.

    In this guide, we started with a basic introduction to shells, bash, and bash scripting. We used simple concepts such as variables, comments, loops, conditional statements, functions, etc., and demonstrated each of them through practical examples. We hope that with the help of this guide, you can easily get started with bash scripting in Linux.

    People are also reading:

    1. PING Command in Linux
    2. SED command in Linux
    3. Find Disk Usage using DU command in Linux
    4. ls Command in Linux
    5. How to use vi editor in Linux?
    6. How to use mkdir command in Linux?
    7. 10 Best Online Linux Terminals
    8. How to Learn Linux?
    9. Find Command in Linux to search for Files
    10. How to List Users in Linux?

    Leave a Comment on this Post

    0 Comments