Lecture 8 - BASH
Lecture 8 - BASH
MCS 2205
8302
Network Programming
Shell Scripting - BASH
11/13/23 1
Shell Scripting
• Multiple Linux Commands Can Be Combined into
a Single Shell Script and saved in an executable
file
• Bash script file starts with the line – example entries in
BASH file are given below
• #!/bin/bash
#!/bin/bash
echo – e “This is a BASH file\n”
userRecords=`cat /etc/passwd`
usersNames=`echo $userRecords | cut –d “:” –f 1`
for var in $userNames do
echo –e “System user: $var\n”
done
11/13/23 2
Shell Scripting
• Loops e.g.
• For loop
• While loop
• Conditionals/constructs e.g.
• If, then, elif, else
• Arrays e.g.
• array=(red green blue yellow black white)
• Variables
• answer=‘Yes’, Yes is stored in $answer
• Math operators
• -ne : Not equal
• -gt : Greater than
• -eq : equal
• -lt : Less than
• == : compare strings
11/13/23 3
Shell Scripting
• Functions
• guessprime() {….}
• User input
• read guess : stores user input in $guess
11/13/23 4
BASH For Loop
Example
#!/bin/bash
for args in {1 2 3 4 5};
do
echo $args
done
11/13/23 5
BASH While Loop
Syntax Example
while [ condition ]; #!/bin/bash
do a=7
# statements while [ $a -gt 4 ];
# commands do
done echo $a
((a--))
done
11/13/23 6
BASH IF Conditional Block
Syntax Example
#!/bin/bash
if CONDITION_1 echo -n "Enter Number: "
read x
then
COMMANDS_1
if [ $x == 0 ]; then
elif CONDITION_2 echo "Number is Zero"
then elif [ $((x%2)) == 0 ]; then
COMMANDS_2 echo "Number is Even"
else else
COMMANDS_3 echo "Number is Odd"
fi
fi
11/13/23 7