Linux Shell Scripting Basics: An Introduction to Shell Scripting in Linux

Linux Shell Scripting Basics: An Introduction to Shell Scripting in Linux

Powerful way to perform repetitive tasks

What is a Shell?

The shell is a critical component in the Linux operating system that serves as a user-kernel interface. When a user logs in to a Linux system, the kernel launches the shell, which acts as an interface between the user and the system. All tasks performed within Linux machines are executed through the shell based on commands input by the user. A shell is an essential tool as it enables direct interaction with the Linux kernel, making it a powerful and essential tool for managing and controlling Linux machines.

Prompts in Shell

Prompts in the shells indicate that the user can issue commands. These prompts are different for different kinds of shells. Whether you are logged in as a root user or non-root user, the prompt in the shell changes accordingly. The prompt also indicates that the shell is ready to take command as inputs.

Types of Shells

  • Bourne Shell

  • Bourne Again Shell

  • C Shell

  • Korn Shell

  • Z Shell

  • Debian Almquist Shell (dash)

All the shells mentioned provide different kinds of features but their major goal is to help the user interact with the kernel through commands.

What are Shell Scripts?

Shell Scripts in Linux help automate repetitive tasks. Whenever you have to execute a bunch of commands shells can take those commands stored in a file and run them automatically so that we don't have to run each command individually.

Suppose your job is to run some commands daily on the Linux machine, so instead of running those commands individually, you can create a script that will contain those commands. Now you can run a single command which will run the script which in turn will execute all the necessary commands.

Run your Shell Script

Suppose you want to execute the following tasks:

  1. Create a file named myfile.txt

  2. Create a directory named 'mydir'

  3. Print uptime of the system

  4. echo "Hello World From Shell Script"

Now one way to do the following tasks is to execute commands individually or we can use shell scripting.

  • Create a file named "myscript.sh"

  • Add the following commands to it:

      touch myfile.txt 
      mkdir mydir 
      uptime 
      echo "Hello World From Shell Script"
    
  • Save and close the file.

  • Give execute permission to the file: chmod +x myscript.sh

  • Now execute the script: bash myscript.sh

By running this script all the tasks mentioned in the script will be executed.

Variables

A variable can be used to store a text that is occurring multiple times in the script. Instead of hardcoding that text, store that text in a variable and use the variable instead.

Rules

  • A variable name must only contain alphanumeric or underscores.

  • It is case-sensitive.

  • "store" and "STORE" are considered different.

Examples

  • Initialize a variable: shop=open

  • Access a variable: echo $shop -> open

  • Use a variable to store the value of another command:

    value=$(echo "HelloWorld")

    echo $value -> HelloWorld

  • echo "Command $value_Java" -> Command HelloWorld_Java

  • ans=`echo hello`

    echo $ans -> hello

  •             val=HelloWorld
                echo $val
                echo $val
                echo $val
    

Best Practice - Variable names must be in lowercase with an underscore to separate words.

Arguments

When you run a shell script you either hard code the values in the script or provide them during the script runtime. Suppose your script does the addition of two numbers, hard coding the values will generate the same result all the time.

Or, values can be provided at runtime. Arguments help in doing this.

Examples

  • Below is the script where you hardcode the values. It will always generate the same result 11. Run the command: bash myscript.sh

      a=5
      b=6
      sum=$(( $a + $b ))
      echo $sum
    
  • Here, the values are passed as arguments.

    Run the command: bash myscript.sh 5 6 The name of the script 'myscript' is stored in a special built-in variable '$0'. The first argument '5' is stored in a variable '$1'. The second argument '6' is stored in a variable '$2'. It can have as many arguments as we want. The next argument value will be stored in the '$3' named variable and so on. The 10th argument value will be stored in the '$10' named variable.

      a=$1
      b=$2
      sum=$(( $a + $b ))
      echo $sum
    
  • Now instead of passing values as arguments you can also prompt the user to enter a value. Place the command read <var-name> inside the script. When this line hits it will wait for the user to give input.

    Run the command: bash myscript.sh

      read a
      read b
      sum=$(( $a + $b ))
      echo $sum
    
  • If you want to prompt the user for input with a message: Place the command read -p "Please enter number: " num -> This will prompt the user for the message and the value will be stored in variables 'a' and 'b'.

    Run the command: bash myscript.sh

      read -p "Enter first number: " a
      read -p "Enter second number: " b
      sum=$(( $a + $b ))
      echo $sum
    

Arithmetic Operations - Examples

  •       expr 4 + 5 -> 9
          expr 4 - 5 -> -1
          expr 4 \* 5 -> 20
          expr 5 / 5 -> 0
    

    Here '\' is included before '*' because '*' is reserved as a default symbol for 'include all' in Linux. To use it as a multiply operator use '\'.

  •       A=4
          B=5
          expr $A + $B -> 9
          expr $A - $B -> -1
          expr $A \* $B -> 20
          expr $A / $B -> 0
    
  •       A=4
          B=5
          echo $(( A + B )) -> 9
          echo $(( A - B )) -> -1
          echo $(( A * B )) -> 20
          echo $(( A / B )) -> 0
    

    Here you don't have to include '\' before '*'.

  •       A=4
          echo $((++A)) -> 5
          echo $((--A)) -> 4
          echo $((A++)) -> 4
          echo $((A--)) -> 5
    
  • If you are using the "expr" statement to perform arithmetic calculations then include space between the operand and any operator you are using. expr $A<space>+<space>$B There should be at least one space between operand and operator if calculations are performed using "expr". While in the case of an echo statement, you can use the operand and operator inside the double brackets in any fashion. echo $((A+B)), echo $((A + B)), echo $((A+ B)), echo $((A +B)), all are valid.

  •             A=15
                B=2
                echo $((A / B)) -> 7 (INTEGER DIVISION)
    
  •             A=15
                B=2
                echo $A / $B | bc -l -> 7.5 (DECIMAL DIVISION)
    

    If you get an error in the above command then run any of the following commands: apt-get install bc or yum install bc. After installing the 'bc' package perform the calculation.

Conclusion

In conclusion, Linux shell scripting is a powerful tool for automating repetitive tasks and streamlining processes. By understanding the basics of shell scripts, variables, and arguments, you can create efficient scripts to perform various tasks on your Linux machine. As you become more proficient, you can explore advanced concepts such as loops and conditions to further enhance your scripting capabilities.

This is the first part of the blog, where I have discussed some basic concepts in shell scripting. I will upload another blog post in which I will cover more advanced concepts, such as loops, conditions, and so on.

Thanks for reading the blog. Connect with me on Twitter.