Lab2 3
Lab2 3
3. calculator :
echo "Enter two numbers:"
read num1 num2
echo "Enter operation (+, -, *, /):"
read op
case $op in
"+") result=$((num1 + num2)) ;;
"-") result=$((num1 - num2)) ;;
"*") result=$((num1 * num2)) ;;
"/") result=$((num1 / num2)) ;;
*) echo "Invalid operation"; exit 1 ;;
esac
if [ -d "$dir" ]; then
mkdir -p "$dest"
cp -r "$dir" "$dest"
echo "Backup completed successfully."
else
echo "The directory $dir does not exist."
LAB 3
12. Read ‘n’ from the user and print the Fibonacci sequence until ‘n’.
echo "Enter the value of n:"
read n
a=0
b=1
echo "Fibonacci Sequence:"
echo $a
echo $b
for ((i=2; i<n; i++)); do
fib=$((a + b))
echo $fib
a=$b
b=$fib
done
13. Say “Hello” to a user and greet them based on the time of the day (Good Morning /
Eve etc.).
hour=$(date +%H)
if [ $hour -lt 12 ]; then
echo "Good Morning!"
elif [ $hour -lt 18 ]; then
echo "Good Afternoon!"
else
echo "Good Evening!"
fi
14. Write a script for printing all file-related information in the present
working directory (size, permissions, etc.).
for file in *; do
if [ -f "$file" ]; then
echo "File: $file"
ls -lh "$file"
fi
done
15. Print the length of each and every string using arrays.
echo "Enter strings separated by space:"
read -a strings
for str in "${strings[@]}"; do
echo "Length of '$str': ${#str}"
done
#!/bin/bash
longest=""
shortest=""
users=("alice" "bob" "charlie" "david")
for user in "${users[@]}"; do
if [ -z "$longest" ] || [ ${#user} -gt ${#longest} ]; then
longest=$user
fi
if [ -z "$shortest" ] || [ ${#user} -lt ${#shortest} ]; then
shortest=$user
fi
done
echo "Longest username: $longest"
echo "Shortest username: $shortest"
17. Generate five random 8-character passwords having alphanumeric
characters.
for i in {1..5}; do
pw=$(tr -dc 'A-Za-z0-9' </dev/urandom | head -c 8)
echo "Password $i: $pw"
done
18. Display the names of all file systems that have less than 10% free space
available.
#!/bin/bash
df -h | awk '$5+0 > 90 {print $1}'
19. Write a script to search whether a user exists on the system or not.