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.
# A shell script to read file line by line
while read line
# $line variable contains current line read from the file
# display $line text on the screen or do something with it.
done < $filename
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…
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.
read -p "Enter your choice [yes/no]:" choice
case $choice in
echo "Thank you"
echo "Your type: Yes"
echo "You type: No"
echo "Sorry, invalid input"
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…
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 is an example script initializes two variables with numeric values. Then perform an addition operation on both values and store results in the third variable.
# Calculate the sum of two integers with pre initialize values
# in a shell script
sum=$(( $a + $b ))
Command Line Arguments In this second example, shell script reads two numbers as command line parameters and perform the addition operation.
# Calculate the sum via command line arguments
# $1 and $2 refers to the first and second argument passed as command line arguments
sum=$(( $1 + $2 ))
echo "Sum is: $sum"
Include Files in Bash Similar to other programming languages which allow to include other files to a file, Bash scripting also allows to include (source) another shell script file to script file. For example, to include config.sh script to current script file use following syntax, where config.sh is available in the same directory of the current script.
Include Shell Script in Other Shell Script For this example, First, I have created a data.sh file with the following content.
Now create another file show.sh, which includes data.sh file.
echo "Welcome $name"
echo "Your id is $id"