Multiple BASH scripts
- Write shell scripts specified in problem 6 at the end of Chapter 16. Test these scripts, and make sure that they work.
- Write shell scripts specified in problem 7 at the end of Chapter 16. Test these scripts, and make sure that they work.
- Write shell scripts specified in problem 13 at the end of Chapter 16. Test these scripts, and make sure that they work.
Solution
task6.sh
#/bin/bash
digits_sum=0
for number in “$@”; do
square=$(($number*$number))
echo -n “$square ”
for i in $(seq 1 ${#square}); do
digits_sum=$(($digits_sum + ${square:i-1:1}))
done
done
echo
echo $digits_sum
task7.sh
#/bin/bash
gateway=$(ip route | grep default | cut -d’ ‘ -f3)
if [[ $(ip route get “$1” | grep -q $gateway) ]]; then
echo “$1 is on the local network”
else
echo “$1 is not on the local network”
fi
task13.sh
#!/bin/bash
functionget_date {
date
}
functionget_listing {
ls
}
functionget_logged_in {
who
}
function quit {
exit 0
}
while true; do
echo “Use one of the following options:”
echo ” d or D: To display today’s date and present time”
echo ” l or L: To see the listing of files in your present working directory”
echo ” w or W: To see who’s logged in”
echo ” q or Q: To quit this program”
echo “Enter your option and hit
read option
case “$option” in
d|D) get_date
;;
l|L) get_listing
;;
w|W) get_logged_in
;;
q|Q) quit
;;
*) echo “Invalid option; try running the program again.”
exit 1
;;
esac
done
exit 0