Assignment 7
- Write a program called valid that prints "yes" if its argument is a valid shell variable name and "no" otherwise.
(Hint: Define a regular expression for a valid variable name and then enlist the aid of grep or sed.)
(Exercise question 1)
Solution:
# check for valid varable name if echo $var | grep '^[A-Za-z_][A-Za-z0-9_]*$' > /dev/null then echo "$var is a valid variable name" else echo "$var is not valid" fi - Write a program called t that displays the time of day in a.m. or p.m. notation rather than in 24-hour clock time.
Use the shell's built-in integer arithmetic to convert from 24-hour clock time.
(Exercise question 2)
Solution:
# change the time format to 12 hour hour=$(date|cut -c12-13) min=$(date|cut -c15-16) if [ "$hour" -eq 0 ] # midnight then hour=12 ampm="am" elif [ "$hour" -eq 12 ] # noon then ampm="pm" elif [ "$hour" -lt 12 ] then ampm="am" else # it is gt 12 hour=$(($hour - 12)) ampm="pm" fi echo "The time is $hour:$min $ampm." - Repeat question 2 using a case statement.
Solution:
# change the time format to 12 hour hour=$(date|cut -c12-13) min=$(date|cut -c15-16) case $hour in 00) hour=12 ampm="am" ;; 12) ampm="pm" ;; 0[1-9]|1[01]) ampm="am" ;; *) hour=$(($hour - 12)) ampm="pm" ;; esac echo "The time is $hour:$min $ampm." - Write a program called isyes that returns an exit status of 0 if its argument is "yes," and 1 otherwise.
For purposes of this exercise, consider y, yes, Yes, YES, and Y all to be valid "yes" arguments.
Write the program using case command.
(Exercise question 4)
Solution:
# exit status 0 if yes # exit status 1 if not yes case $1 in [yY]|[yY]es|YES) exit ;; *) exit 1 ;; done