Read file line by line?

Shell Script to Read File

Brief: This example will help you to read a file in a bash script. This tutorial contains two methods to read a file line by line using a shell script.

Method 1 – Using simple loop

You can use while read loop to read a file content line by line and store into a variable.

Note – In above script line is a variable only. You can use any variable name in place of the line of your choice.

Method 2 – Using IFS

The IFS (Internal Field Separator) is a special shell variable used for splitting words and line based on its value. The default value is .

Bash – Case

Switch (Case) Statment in Bash

The case statement is useful and processes faster than an else-if ladder. Instead of checking all if-else conditions, the case statement directly select the block to execute based on an input.

Create the first program using the case statement in a shell script. The program takes input from the user and executes statements based on the input value.

Save the above script in case1.sh and execute the script on bash shell.

chmod +x case1.sh
./case1.sh
Enter your choice [yes/no]:yes
Thank you
Your type: Yes


./case1.sh
Enter your choice [yes/no]:no
Ooops
You type: No

./case1.sh
Enter your choice [yes/no]:anything
Sorry, invalid input

Script Execution Process:

  • Set the execute permission on shell script.
  • Executed the script first time and input “yes” to choice variable. Case matches the string with available options yes). Then executed code block under yes option.
  • Executed the script second time and input “no” to choice variable. Case matches the string with available options no). Then executed code block under no option.
  • Executed the script third time and input “anything” to choice variable. Case found not matches under available options for this string. In this situation case uses wildcard *) and executed statments under it.

Multple Strings in Case Options

You can define more than one string in the matching pattern under case statement in shell scripting. Check sample script here:

Patterns Matching in Case Statement

You can use wildcard characters like *,? and [] with the case statement. But still, some of the braces expansion still not work. Now, you can set shopt -s extglob to use extended pattern matching.

Save above script in a shell script and execute it with various inputs and study about its execution.

Concatenate string variables

Brief: This example will help you to concatenate two or more strings variable in a bash script. This tutorial helps you with multiple shell script examples of concatenating strings in a shell script.

The first example is a general way to concatenate variables of string. You can simply write all the variable one after another:

Output:

Welcome TecAdmin!

Another Example

You can also use += operator to concatenate two strings and store results in the first string.

Output:

Welcome TecAdmin!

One More Example

Use another example with one string variable with user input and another fixed strings.

Script execution result:

Enter your name: Rahul
Welcome Rahul

Using {} with Variables

In some situation, you may face issue while concatenating one string with another string variable as shown in below example. Here you need to use curly braces around variable name.

Output

.sql
backup_03132018.sql

You can see that first output if incorrect and second output is correct using {} around variable name.

Check if two strings are equal?

Brief: This example will help you to understand to check if two strings are equal in a bash script. This shell script accepts two string in variables and checks if they are identical.

Bash Strings Equal Check:

  • Use == operator with bash if statement to check if two strings are equal.
  • You can also use != to check if two string are not equal.
  • You must use single space before and after the == and != operators.

Example:

In this script two variables are initialized with predefined strings. Now check if both strings are equal or not with == operator.

Output:

Strings are equal

Another Example:

Use below sample shell script to take input from the user and check if given strings are equal or not.

Script execution results:

First Run:
StEnter first string: welcome bash
Enter second string: welcome bash
Strings are equal

Second Run:
Enter first string: Welcome bash
Enter second string: hello bash
Strings are not equal

Add two numbers?

Shell Script to Add Two Integers

Brief: This example will help you to understand to add two numbers in the bash script. This script takes the input of two numbers from the user and prints the sum of both numbers.

This sample script initializes two variables with numeric values. Then add two number variables and store in another variable.

The below shell script uses read command to prompt the user for two numbers. Then calculate the sum of given numbers and store to another variable.

Output:

Enter first number: 12
Enter second number: 14
Sum is: 26

Bash – Functions

Functions in Bash

A function which can also be referred to as subroutine or procedure is a block of code used for specific tasks. The function also has a property called re-usability. Bash script also provides functions.

Syntax:

funcationName(){    
  // scope of function
}

functionName  //calling of function

#1. Bash – Create Function Example

Create your first function in shell script showing output “Hello World!”. Create a shell script “script.sh” using following code.

#!/bin/bash

funHello(){
    echo "Hello World!";
}

# Call funHello from anywhere in the script like below

funHello

Le’t execute script

$ ./script.sh

Hello World!

#2. Bash – Function with Argument

The passing argument to functions is similar to pass an argument to command from shell. Functions receives arguments to $1,$2… etc. Create a shell script using following code.

#!/bin/bash

funArguments(){
   echo "First Argument: " $1
   echo "Second Argument: " $2
   echo "Third Argument: " $3
   echo "Fourth Argument: " $4
}

# Call funArguments from anywhere in the script using parameters like below

funArguments 1 Welcome to TecAdmin 

Let’s execute the script with the bash shell.

$ ./script.sh

First Argument : 1
Second Argument : Welcome
Third Argument : to
Fourth Argument : TecAd,om

For more detailed uses of function in bash scripts visit here.

Bash – For Loop

For Loop in Bash

As any other programming language, shell scripts also support for loops to do the repetitive tasks. Read this tutorial to understand uses of for loop with examples.

Syntax:

for VARIABLE in PARAM1 PARAM2 PARAM3
do
  // scope of for loop
done 

for loop executes for each parameter once defined. The VARIABLE is initialized with the parameter’s value which can be accessed in inside the for loop scope. These parameters can be any number, string etc.

#1. Bash – For Loop Example

Check below basic for loop which iterates 5 times.

You can also define a range with for loop in the bash script with numeric values.

The arguments can be also a string like:

#2. Bash – For Loop in C Style

You can also write for loop in bash script similar to for loop in c programming. For example to print 1 to 10 numbers.

#3. Bash – For Loop with Files

You can access filenames one by one in for loop under the specified directory. For example, read all files from the current directory.

The above loop will iterate the number of times as the number of files available. It will select one by file in each iteration.

Bash – String Comparisons

Bash String Comparisons

Use double equals ( == ) operator to compare strings inside square brackets []. Using this option you simply test if two given strings are equals or not inside bash shell scripts.

Example Syntax:

if [ "$str1" == "$str2" ]     # True if equal
if [ "$str1" != "$str2" ]     # True if not equal

Example:

For example to compare two string are equal or not.

if [ "hello" == "hello" ]    ## True
if [ "hello" == "hello1" ]   ## False

if [ "hello" != "hello" ]    ## False
if [ "hello" != "hello1" ]   ## True

Take input of two string in a script and compare if both are same or not, using if statement.

Bash – Numeric Comparisons

Bash Numeric Comparisons

Under bash shell, you can directly compare numeric values using double parentheses like “((expression))”.

Syntax:

((n1 > n2))

Example:

Compare two values and check if one is greater than other value. Write below script in compare.sh file.

Now execute this script using bash shell

$ chmod +x ./compare.sh
$ ./compare.sh
True

Bash – Numeric Comparisons Operators

You can try with many more comparison operators in bash shell to compare two numeric values.

((n1 == n2))    ## n1 is equals to n2
((n1 != n2))    ## n1 is not equals to n2
((n1 > n2))     ## n1 is greater than n2
((n1 >= n2))    ## n1 is greater or equals to n2
((n1 < n2))     ## n1 is smaller than n2
((n1 <= n2))    ## n1 is smaller than or equals to n2

Bash – Quotes

Quotes in Bash

This is a standard practice to quote the string in any programming language. Quotes are used to deal with the texts, filenames with a space character. Read this tutorial to understand the differences between single quote and double quotes.

Quote with String

While working with simple texts and string, there are no different in using a single quote or double quote.

The above script will run without any error and print the messages and create both directories.

Quote with Variables

Just remember that the shell variable expansion will work with double quotes only. If you define any variable in single quote will not work.

#!/bin/bash

NAME="Welcome TecAdmin"

echo "$NAME"
echo '$NAME'

Now execute this script. The first echo will print the value of variable ie “Welcome TecAdmin”, But the second variable will print only $NAME due to enclosed in single quote.