Linux and Shell Programming - Lab Exercises, Exercises of Computer Science

Linux and Shell Programming - Lab Exercises for II year BCA and B.Sc. C.Sc., Bharathiyar Uty.

Typology: Exercises

2018/2019

Uploaded on 09/09/2019

Sujatha1969
Sujatha1969 🇮🇳

4.6

(7)

5 documents

1 / 31

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
I. For loop examples
1. Simple for loop
for (( counter=10; counter>0; counter-- ))
do
echo -n "$counter "
done
printf "\n"
2. Reading Array Variable
You can use for loop to iterate the values of an array. Create a new bash file
named loop2.sh with the following code.
ColorList=("Blue Green Pink White Red")
for color in $ColorList
do
if [ $color == 'Pink' ]
then
echo "My favorite color is $color"
fi
done
3. Reading Command-line arguments
Command-line arguments values can be iterated by using for loop in bash. Create a new bash file
named loop3.sh with the following code.
for myval in $*
do
echo "Argument: $myval"
done
4. Finding odd and even number using three expressions
The most common syntax of for loop is three expression syntax. First expression indicates
initialization, second expression indicates termination condition and third expression indicates
increment or decrement. Create a new file named loop4.sh to check the script.
for (( n=1; n<=5; n++ ))
do
if (( $n%2==0 ))
then
echo "$n is even"
else
echo "$n is odd"
fi
done
5. Reading file content
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f

Partial preview of the text

Download Linux and Shell Programming - Lab Exercises and more Exercises Computer Science in PDF only on Docsity!

I. For loop examples

  1. Simple for loop

for (( counter=10; counter>0; counter-- )) do echo -n "$counter "

done

printf "\n"

2. Reading Array Variable You can use for loop to iterate the values of an array. Create a new bash file named loop2.sh with the following code. ColorList=("Blue Green Pink White Red") for color in $ColorList do if [ $color == 'Pink' ] then echo "My favorite color is $color" fi done 3. Reading Command-line arguments Command-line arguments values can be iterated by using for loop in bash. Create a new bash file named loop3.sh with the following code.

for myval in $* do echo "Argument: $myval" done

4. Finding odd and even number using three expressions The most common syntax of for loop is three expression syntax. First expression indicates initialization, second expression indicates termination condition and third expression indicates increment or decrement. Create a new file named loop4.sh to check the script.

for (( n=1; n<=5; n++ )) do if (( $n%2==0 )) then echo "$n is even" else echo "$n is odd" fi done

5. Reading file content

You can use for loop to read content of any file by using ‘cat’ command. Suppose, you have a file named ‘ weekday.txt ’ which contains the name of all week days. Now, create a bash file named loop5.sh to read the content of the file. i= for var in cat weekday.txt do echo "Weekday $i: $var" ((i++)) done

II) User input examples

6. Using read command with options -p option is used with read command to display some helpful message for the user related to input. -s option is used to hide the text from the terminal which will be typed by the user. This is called silent mode and used for password data. The following example shows the use of both options.

Type your Login Information

read -p 'Username: ' user read -sp 'Password: ' pass

if (( $user == "admin" && $pass == "12345" ))

then echo -e "\nSuccessful login"

else

echo -e "\nUnsuccessful login"

fi

7. Using read command to take multiple inputs If you want to take multiple inputs at a time then you have to use read command with multiple variable names. In the following example, four inputs are taken in four variables by using read command.

# Taking multiple inputs echo "Type four names of your favorite programming languages" read lan1 lan2 lan3 lan echo "$lan1 is your first choice" echo "$lan2 is your second choice" echo "$lan3 is your third choice" echo "$lan4 is your fourth choice"

8. Using read command with the time limit If you want to set time restricted input for the user then you have to use -t option with a read command. Here, time is counted as second. In the following example, the program will

echo "Enter your lucky number" read n

if [ $n -eq 101 ]; then echo "You got 1st prize" elif [ $n -eq 510 ]; then echo "You got 2nd prize" elif [ $n -eq 999 ]; then echo "You got 3rd prize"

else echo "Sorry, try for the next time" fi

IV) Case..esac statement

12. Using Case Statement:

Case statement is used as the alternative of if-elseif-else statement. The starting and ending block of this statement is defined by ‘ case ’ and ‘ esac ’. Create a new file named, ‘ case_example.sh ’ and add the following script. The output of the following script will be same to the previous else if example.

echo "Enter your lucky number" read n case $n in

echo echo "You got 1st prize" ;;

echo "You got 2nd prize" ;;

echo "You got 3rd prize" ;; *) echo "Sorry, try for the next time" ;; esac

V) Command line arguments

13. Get Arguments from Command Line:

Bash script can read input from command line argument like other programming language. For example, $1 and $2 variable are used to read first and second command line arguments. Create a file named “ command_line.sh ” and add the following script. Two argument values read by the following script and prints the total number of arguments and the argument values as output.

echo "Total arguments : $#" echo "1st Argument = $1" echo "2nd argument = $2"

  1. Get arguments from command line with names:

How you can read command line arguments with names is shown in the following script. Create a file named, ‘ command_line_names.sh’ and add the following code. Here, two arguments, X and Y are read by this script and print the sum of X and Y.

for arg in "$@" do index=$(echo $arg | cut -f1 -d=) val=$(echo $arg | cut -f2 -d=) case $index in X) x=$val;;

Y) y=$val;; *) esac done ((result=x+y)) echo "X+Y=$result"

  1. Sending three numeric values as arguments Create a bash file and add the following code. The script will receive three argument values and store in $1, $2 and $3. It will count the total number of arguments, print argument values with loop and without loop. Lastly, print the sum of all argument values.

# Counting total number of arguments echo "Total number of arguments : $#"

# Reading argument values individually echo "First argument value : $1" echo "Second argument value : $2" echo "Third argument value : $3"

# Reading argument values using loop for argval in "$@" do echo -n "$argval " done

# Adding argument values sum=$(($1+$2+$3))

# print the result

You can easily combine string variables in bash. Create a file named “ string_combine.sh ” and add the following script to check how you can combine string variables in bash by placing variables together or using ‘+’ operator.

string1="Linux" string2="Hint" echo "$string1$string2" string3=$string1+$string string3+=" is a good tutorial blog site" echo $string

  1. Get substring of String:

Like other programming language, bash has no built-in function to cut value from any string data. But you can do the task of substring in another way in bash that is shown in the following script. To test the script, create a file named ‘ substring_example.sh ’ with the following code. Here, the value, 6 indicates the starting point from where the substring will start and 5 indicates the length of the substring.

Str="Learn Linux from LinuxHint" subStr= ${Str:6:5} echo $subStr

VII) Arithmatic operations

  1. Using ‘expr’ command The oldest command for doing arithmetic operations in bash is ‘ expr ’. This command can work with integer values only and prints the output directly in the terminal. You have to use space with each operand when you want to use ‘ expr’ command to do any mathematical operations. Create a bash file and add the various ‘expr’ commands to check how the ‘expr’ command works.

# Works as string expr '10 + 30'

# Works as string expr 10+

#Perform the addition expr 10 + 30

#Find out the remainder value expr 30 % 9

#Using expr with backtick myVal1=expr 30 / 10 echo $myVal

#Using expr within command substitute

myVal2=$( expr 30 - 10 ) echo $myVal

  1. Using ‘let’ command ‘let’ is another built-in command to do arithmetic operations in bash. ‘let’ command can’t print the output to the terminal without storing the value in a variable. But ‘let’ command can be used to remove the other limitations of the ‘expr’ command. Create a bash file and add the following code for seeing how the ‘let’ command works.

# Multiplying 9 by 3 let val1=9* echo $val

# Dividing 8 by 3 let "val2 = 8 / 3" echo $val

# Subtracting 3 from 9 let val3=9- echo $val

# Applying increment let val4= let val4++ echo $val

# Using argument value in arithmetic operation let "val5=50+$1" echo $val

  1. Using double brackets You can perform any arithmetic operation in bash without using any command. Here, double brackets are used to do the arithmetic tasks and using double bracket for executing mathematical expressions is more flexible than commands like ‘expr’ or ‘let’. Create a bash file and add the following code to test the arithmetic operations by using double brackets.

# Calculate the mathematical expression val1=$((10*5+15)) echo $val

# Using post or pre increment/decrement operator ((val1++)) echo $val val2= ((--val2)) echo $val

  1. function with Parameters:

Bash can’t declare function parameter or arguments at the time of function declaration. But you can use parameters in function by using other variable. If two values are passed at the time of function calling then $1 and $2 variable are used for reading the values. Create a file named ‘ function|_parameter.sh ’ and add the following code. Here, the function, ‘ Rectangle_Area’ will calculate the area of a rectangle based on the parameter values.

Rectangle_Area() { area=$(($1 * $2)) echo "Area is : $area" }

Rectangle_Area 10 20

  1. Pass Return Value from Function:

Bash function can pass both numeric and string values. How you can pass a string value from the function is shown in the following example. Create a file named, ‘ function_return.sh ’ and add the following code. The function, greeting() returns a string value into the variable, val which prints later by combining with other string. function greeting() {

str="Hello, $name" echo $str }

echo "Enter your name" read name

val=$(greeting) echo "Return value of the function is $val"

  1. Using Global Variable

Bash function can return a string value by using a global variable. In the following example, a global variable, ‘retval’ is used. A string value is assigned and printed in this global variable before and after calling the function. The value of the global variable will be changed after calling the function. This is a way of returning string value from a bash function.

function F1()

{

retval='I like programming'

}

retval='I hate programming'

echo $retval

F

echo $retval

Create a bash file named func1.sh with the above code and run the script from the terminal. Here, the output ‘I like programming’ is assigned and printed after function call.

  1. Using Function Command

You can receive the return value of a bash function and store it in a variable at the time of calling. In the following example, a local variable, retval is used and the value of the local variable is return by the function F2 is assigned in a global variable, getval which is printed later. function F2()

{

local retval='Using BASH Function' echo "$retval"

}

getval=$(F2)

echo $getval

Create a bash script named func2.sh with the above code and run the script.

  1. Using Variable

In the following example, the return value of the function is set based on the argument variable of the function. Here, a value is passed to the function F3 by using an argument variable, getval at the time of function calling. After checking conditional statement, the return value is assigned and printed.

function F3()

{

local arg1=$

if [[ $arg1 != "" ]]; then retval="BASH function with variable" else echo "No Argument" fi

}

getval1="Bash Function"

F3 $getval

echo $retval

getval2=$(F3)

echo $getval

Create a bash script named func3.sh with the above code and run the script.

If you want to create non-exist path forcefully by creating all non-exist directories mentioned in the path from terminal then run ‘ mkdir ’ command with ‘-p ’ option. $ mkdir -p /picture/newdir/test

Now, check the directories are created or not by running the following commands.

$ cd picture $ ls -R

32. Create directory with permission

When you create a new directory then a default permission is set for the newly created directory.

Create a new directory and check the default permission by executing following commands. ‘ stat’ command is used to check current permission of any existing directory. The default directory permission is ‘ rwxr-xr-x ’. This indicates directory owner has all permissions, and group users and others users have no write permission. $ mkdir newdir $ stat newdir1/

‘-m’ option is used to set the directory permission at the time of directory creation. Run the following commands to create a directory with all permissions and check the permission using ‘stat’ command. The output shows all types of users have all permissions.

  1. Create directory using script

You can test any directory is exist or not by using bash script. Create a bash file and add the following code to create the new directory after testing the directory is exist or not by using ‘-d ’ option. If the directory exists then it will show the message, “Directory already exists”, otherwise new directory will be created.

echo -n "Enter the directory name:" read newdirname if [ -d "$newdirname" ]; then echo "Directory already exists" ; else mkdir -p $newdirname; echo "$newdirname directory is created" fi

X) File operations

  1. Read a File:

You can read any file line by line in bash by using loop. Create a file named, ‘ read_file.sh ’ and add the following code to read an existing file named, ‘ book.txt ’.

file='book.txt' while read line; do echo $line done < $file

  1. Reading file content using script Create a bash file and add the following code to read the content of a particular file. Here, an existing filename is stored in $filename variable and $n variable is used to keep the value of the line number of that file. Like previous example, while loop is used to read this file with line number.

filename='company.txt' n= while read line; do # reading each line echo "Line No. $n : $line" n=$((n+1)) done < $filename

  1. Passing filename from the command line and reading the file Create a bash file and add the following script. This script will take the filename from the command line argument. First argument value is read by the variable $1 which will contain the

else echo "File does not exist" fi Run the following commands to check the existence of the file. Here, book.txt file exists and book2.txt is not exist in the current location.

XI) Simple example scripts

40. # Q1.Script to sum to nos

if [ $# -ne 2 ] then echo "Usage - $0 x y" echo " Where x and y are two nos for which I will print sum" exit 1 fi echo "Sum of $1 and $2 is expr $1 + $2"

41. Printing username, login id etc

#!/bin/bash

# Write a shell script called hello which output the following:

# + Your username

# + The time and date

# + Who is logged on

# + also output a line of asterices (*******) after each section

# function to display a line of asterices

function line(){

echo "*************************************************"

}

echo "Your username : $(echo $USER)"

line # call function

echo "Current date and time : $(date)"

line

echo "Currently logged on users:"

who

line

42. script to print given number in reverse order, for eg. If no is 123 it must print as 321.

if [ $# -ne 1 ] then echo "Usage: $0 number" echo " I will find reverse of given number" echo " For eg. $0 123, I will print 321" exit 1 fi

n=$ rev= sd=

while [ $n -gt 0 ] do sd=expr $n % 10 rev=expr $rev \* 10 + $sd n=expr $n / 10 done echo "Reverse number is $rev"

43. script to print contains of file from given line number to next given number of lines. For e.g.

If we called this script as Q13 and run as

$ Q13 5 5 myf , Here print contains of 'myf' file from line number 5 to next 5 line of that file.

if [ $# -eq 0 ] then echo "$0:Error command arguments missing!" echo "Usage: $0 start_line uptoline filename" echo "Where start_line is line number from which you would like to print file" echo "uptoline is line number upto which would like to print" echo "For eg. $0 5 5 myfile" echo "Here from myfile total 5 lines printed starting from line no. 5 to" echo "line no 10." exit 1 fi

Look for sufficent arg's

start_mc()

{ if which mc > /dev/null ; then mc echo "Midnight commander, Press a key.. ." read else echo "Error: Midnight commander not installed, Press a key.. ." read fi return }

Function to start editor

start_ed() { ced=$ if which $ced > /dev/null ; then $ced echo "$ced, Press a key.. ." read else echo "Error: $ced is not installed or no such editor exist, Press a key.. ." read fi return }

Function to print help

print_help_uu() { echo "Usage: $0 -c -d -m -v {editor name}"; echo "Where -c clear the screen"; echo " -d show dir"; echo " -m start midnight commander shell"; echo " -e {editor}, start {editor} of your choice"; return }

Main procedure start here

Check for sufficent args

if [ $# -eq 0 ] ; then

print_help_uu exit 1 fi

Now parse command line arguments

while getopts cdme: opt do case "$opt" in c) cls;; d) show_ls;; m) start_mc;; e) thised="$OPTARG"; start_ed $thised ;; ?) print_help_uu; exit 1;; esac done

  1. Write script called sayHello, put this script into your startup file called .bash_profile, the

script should run as soon as you logon to system, and it print any one of the following message

in infobox using dialog utility, if installed in your system, If dialog utility is not installed then

use echo statement to print message : -

Good Morning / Good Afternoon/ Good Evening , according to system time.

temph=date | cut -c12-13 dat=date +"%A %d in %B of %Y (%r)"

if [ $temph -lt 12 ] then mess="Good Morning $LOGNAME, Have nice day!" fi

if [ $temph -gt 12 -a $temph -le 16 ] then mess="Good Afternoon $LOGNAME" fi

if [ $temph -gt 16 -a $temph -le 18 ] then mess="Good Evening $LOGNAME" fi

if which dialog > /dev/null then dialog --backtitle "Linux Shell Script Tutorial" --title "(-: Welcome to Linux :-)"\