Lab 5
Lab 5
Technology
Rahim Yar Khan
Department Of Computer Engineering
Tips:
For example, the $ character represents the process ID number, or PID, of the current
shell.
echo $$
The following table shows a number of special variables that you can use in your
shell scripts −
1
$0
The filename of the current script.
2
$n
These variables correspond to the arguments with which a script was invoked. Here n is a
positive decimal number corresponding to the position of an argument (the first argument is $1,
the second argument is $2, and so on).
3
$#
The number of arguments supplied to a script.
4
$*
All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1
$2.
5
$@
All the arguments are individually double quoted. If a script receives two arguments, $@ is
equivalent to $1 $2.
Example:
To run script:
We run it via:
bash test.sh
Result:
Case Statements:
Basic Syntax:
Example:
case $number in
1)
echo "You selected option 1"
;; //Each case must end with double colon.
2)
echo "You selected option 2"
;;
3)
echo "You selected option 3"
;;
*) // Default case //
echo "Invalid option! Please choose a number between 1 and 3."
;;
esac // ending of case statement
Create a shell script that provides a basic menu for choosing a fruit.
1. Apple
2. Banana
3. Cake
4. Class
case $choice in
1)
;;
2)
;;
3)
;;
4)
;;
*)
;;
esac
Loops in Shell
For Loop
While Loop
Until Loop
Select Loop
1. For Loop:
The for loop is used to iterate over a list of items or a range of
numbers. It allows you to execute a block of commands multiple times.
There are two for loop in Shell
1) Iterating over a List 2) Iterating over a Range
Example:
Iterating over a List:
It is same as For Each Loop as in JAVA.
do
echo "I like $fruit"
done // Completing loop