How to Create Simple Shell Scripts in Linux

How to Create Simple Shell Scripts in Linux

Write only for if statement, explain only if statement.

Shell scripting is one of the most interesting concept in Linux. Shell script is a computer program that contains a list of command that run by the Unix/Linux shell. In simple words, we can say that the shell script is a file which content a variety of command which is executed line by line. Shell script usually have comments to explain the commands or steps. With shell scripting we can perform a variety of task like data manipulation, data processing, text printing etc.

In this tutorial, we will learn some basic shell scripting operation.

Create a Simple Shell Script

To create shell script, we need an editor. You can use any type of test editor, GUI-based editor or command-line based editor. In this tutorial, we will use Vim command-line text editor.

We will start the shell scripting by creating a simple script to display “Hello Linuxpanda”.

First create a script file with .sh extension. Run the following command to create the script file.

vim first.sh

Copy and paste the following in the script file.

#!/bin/bash
echo "Hello Linuxpanda"
#It will print the Hello Linuxpanda on the terminal
  • #!/bin/bash – It is known as she-bang (shebang) header. It tells the interpreter that the data inside the script file is written for bash, so execute the script file in bash script.
  • Echo command is used to print “Hello Linuxpanda” on terminal.
  • ‘#’ in the third line is used to comment the line. A comment is used to describe that what a shell script will do. Comment is preceded by the “#” symbol. Comments are not executed when the script run.

Grant the execution permission to the script. Run the following command to grant the execution permission by using the chmod command.

chmod +x  first.sh

Now run the script with the following command. We can run the script in three ways. Use anyone of them.

bash first.sh
OR
sh first.sh
OR
./first.sh

Use Conditional Statements in Shell Script

The conditional statement is used in most of the languages like C, C++, Python etc. Conditional statement is used to do decision-making tasks. If statement is also used in shell script to perform automated tasks. It is used to test single or multiple conditions.

The following types of conditional statements can be used in bash.

  1. if statement
  2. if else statement
  3. if elif statement
  4. Nested if statement
  5. case statement

Syntax

Example of an if Statement Only

The if statement can be used to test single or multiple conditions. We will start off with the fundamental use of the if statement to test a single condition. The if statement is defined by the if ... fi blocks.

if commandthen   statementfi

Let’s take a look at the shell script below.

#!/bin/bashecho 'Enter the score'read xif [[ $x == 70 ]]; then  echo 'Good job!'fi

The above shell script prompts the user to provide a score that is then stored in a variable x. If the score corresponds to 70, the script returns the output “Good job!”. The comparison operator == is used to test if the score entered, which is stored in the variable x, is equivalent to 100.

if Statement in Shell Script
if Statement in Shell Script

Other comparison operators you can use include:

  • -eq – Equal to
  • -ne – Not equal to
  • -lt – Less than
  • -le – Less than or equal to
  • -lt – Less than
  • -ge – Greater than or equal to

For example, the if-statement block below prints out ‘Work Harder’ if the input score is any value less than 50.

if [[ $x -lt 50 ]]; then  echo 'Work Harder!'fi
if Statement in Shell Script
if Statement in Shell Script

Example of an if-else Statement

For situations where you have 2 possible outcomes: – whether this or that – the if-else statement comes in handy.

if commandthen  statement1else  statement2fi

The script below reads the input score and checks whether it is greater than or equal to 70.

If the score is greater than or equal to 70, you get a ‘Great job, You passed!’ message. However, if the score falls below 70, the output ‘You failed’ will be printed.

#!/bin/bashecho 'Enter the score'read xif [[ $x -ge 70 ]]; then  echo 'Great job, You passed!'else  echo  'You failed'fi
if-else statement in Shell Script
if-else statement in Shell Script

Example of an if-elif-else Statement

In scenarios where there are multiple conditions and different outcomes, the if-elif-else statement is used. This statement takes the following format.

if condition1then  statement1elif condition2then  statement2else  statement3fi

For example, we have a script for a lottery that checks if the number entered is either 90, 60 or 30.

#!/bin/bashecho 'Enter the score'read xif [[ $x -eq 90 ]];then  echo “You have won the First Prize”elif [[ $x -eq 60 ]];then  echo “You have won the Second Prize”elif [[ $x -eq 30 ]];then   echo “You have won the Second Prize”else  echo “Please try again”fi
if-elif-else statement
if-elif-else statement

3. Using the If Statement with AND Logic

You can use the if statement alongside the AND logic operator to execute a task if two conditions are satisfied. The && operator is used to denote the AND logic.

#!/bin/bashecho 'Please Enter your user_id'read user_idecho 'Please Enter your tag_no'read tag_idif [[ ($user_id == “tecmint” && $tag_id -eq 3990) ]];then  echo “Login successful”else  echo “Login failure”fi

5. Using the If Statement with OR Logic

When using the OR logic, that is represented by || symbol, either one of the conditions needs to be satisfied with the script to give the expected results.

#!/bin/bashecho 'Please enter a random number'read numberif [[ (number -eq 55 || number -eq 80) ]];then echo 'Congratulations! You’ve won'else echo 'Sorry, try again'fi
If statement with OR logic
If statement with OR logic

Use Looping Constructs

Bash loops allow users to perform a series of tasks until a certain result is achieved. This comes in handy in performing repetitive tasks. In this section, we shall have a peek at some of the loops which you’d also find in other programming languages.

While loop

This is one of the easiest loops to work with. The syntax is quite simple:

while  <some test>do commandsdone

The while loop below lists all the numbers from 1 to 10 when executed.

#!/bin/bash# A simple while loopcounter=1while [ $counter -le 10 ] doecho $counter ((counter++))done

Let’s disscuss the while loop:

The variable counter is initialized to 1. And while the variable is less than or equal to 10, the value of the counter will be incremented until the condition is satisfied. The line echo $counter prints all the numbers from 1 to 10.

While loop in Shell Script
While loop in Shell Script

For loop

Like the while loop, a for loop is used to execute code iteratively. I.e. repeat code execution as many times as possible defined by the user.

The syntax is:

for var in 1 2 3 4 5 Ndo command1 command2done

The for loop below iterates through 1 right through 10 and processes their values on the screen.

For loop in Shell Script
For loop in Shell Script

A better way to achieve this is to define a range using the double curly braces { } as shown instead of typing all the numbers.

#!/bin/bash# Specify range in a for loopfor num in {1..10}do  echo $numdone

Bash Positional Parameters

A positional parameter is a special variable that is referenced in the script when values are passed on the shell but cannot be assigned. Positional parameters run from $0 $1 $2 $3 …… to $9. Beyond the $9 value, the parameters have to be enclosed in curly brackets e.g ${10}, ${11} … and so on.

When executing the script, the first positional parameter which is $0 takes the name of the shell script. The $1 parameter takes the first variable that is passed on the terminal, $2 takes the second, $3 the third and so on.

Let’s create a script test.sh as shown.

#!/bin/bashecho "The name of the script is: " $0echo "My first name is: " $1echo "My second name is: " $2

Next, execute the script and provide the first and second name as the arguments:

# bash test.sh James Kiarie
Bash Positional Parameter
Bash Positional Parameter

From the output, we can see that the first variable that is printed is the name of the shell script, in this case, test.sh. Thereafter, the names are printed out corresponding to the positional parameters defined in the shell script.

Positional parameters are useful in that they help you customize the data being entered instead of explicitly assigning a value to a variable.

Shell Command Exit Codes

Let’s begin by answering a simple question, What is an exit code?

Every command executed on the shell by a user or shell script has an exit status. An exit status is an integer.

An exit status of 0 implies that the command executed successfully without any errors. Anything between 1 to 255 shows that the command failed or did not execute successfully.

To find the exit status of a command, use the $? Shell variable.

An exit status of 1 points to a general error or any impermissible errors such as editing files without sudo permissions.

An exit status of 2 points to incorrect usage of a command or builtin shell variable.

The 127 exit status points to an illegal command which usually yields the ‘command not found’ error.

Find Exit Status of Command
Find Exit Status of Command

Processing Output of Shell Commands within a Script

In bash scripting, you can store the output of a command in a variable for future use. This is also referred to as shell command substitution and can be achieved in the following ways.

variable=$(command)ORvariable=$(/path/to/command)ORvariable=$(command argument 1 argument 2 ...)

For example, you can store the date command in a variable called today and call the shell script to reveal the current date.

#!/bin/bashtoday=$(date)echo “Today is $today”
Print Date Using Shell Script
Print Date Using Shell Script

Let’s take another example. Suppose you want to find the valid login users on your Linux system. How would you go about it? First, the list of all the users (both system, process, and login users) is stored in the /etc/passwd file.

To view the file, you’d need to use the cat command. However, to narrow down to log in users, use the grep command to search for users with the /bin/bash attribute and use the cut -c 1-10 command as shown to display the first 10 characters of the names.

We have stored the cat command to the login_users variable.

#!/bin/bashlogin_users=$(cat /etc/passwd | grep /bin/bash | cut -c 1-10)echo 'This is the list of login users:echo $login_users
List Logged in Users
List Logged in Users

This brings our tutorial on creating simple shell scripts to an end. We hope you found this valuable.