Lab 3 notes
Lab 3 notes
Sure! Here's a breakdown of each script from Lab 03, with a detailed explanation of what it does
and how it works, including every flag, parameter, and concept used:
Task 1: Conditionals
1. exists.sh
#!/bin/bash
read -p "Enter filename: " fname
if [ -f "$fname" ]; then
echo "File '$fname' exists."
else
echo "File '$fname' does not exist."
fi
2. go.sh
Purpose: Navigates into a directory, shows file contents if it exists, or creates a new directory.
#!/bin/bash
read -p "Enter name: " name
if [ -d "$name" ]; then
cd "$name"
echo "Entered directory $name"
elif [ -f "$name" ]; then
cat "$name"
else
mkdir "$name"
echo "Directory $name created."
fi
#!/bin/bash
case $1 in
Sunday|Monday|Tuesday|Wednesday|Thursday)
echo "This is a workday";;
Friday|Saturday)
echo "This is a weekend";;
*)
echo "This is not a day";;
esac
4. addtwo.sh
#!/bin/bash
sum=$(echo "$1 + $2" | bc)
echo "Sum: $sum"
5. max.sh
#!/bin/bash
if [ $1 -ge $2 ] && [ $1 -ge $3 ]; then
echo "$1 is the largest."
elif [ $2 -ge $1 ] && [ $2 -ge $3 ]; then
echo "$2 is the largest."
else
echo "$3 is the largest."
fi
#!/bin/bash
fact=1
for (( i=1; i<=$1; i++ ))
do
fact=$((fact * i))
done
echo "Factorial: $fact"
2. sumlist.sh
#!/bin/bash
sum=0
for num in "$@"
do
sum=$((sum + num))
done
echo "The total sum is: $sum"
3. guess.sh
#!/bin/bash
secret=$(( (RANDOM % 100) + 1 ))
attempts=0
while true
do
read -p "Enter your guess: " guess
((attempts++))
if [ "$guess" -lt "$secret" ]; then
echo "Too Low!"
elif [ "$guess" -gt "$secret" ]; then
echo "Too High!"
else
echo "Correct! You guessed in $attempts attempts."
break
fi
done
Task 3: Functions
multiops.sh
#!/bin/bash
add() {
echo "Sum: $(($1 + $2))"
}
sum() {
total=0
for n in "$@"; do
total=$((total + n))
done
echo "Sum of list: $total"
}
fac() {
f=1
for (( i=1; i<=$1; i++ )); do
f=$((f * i))
done
echo "Factorial: $f"
}
Let me know if you'd like each script exported separately into files or zipped for submission!