Lab Writeup Write a script called \'parser with the following usage USMGEi parse
ID: 3585176 • Letter: L
Question
Lab Writeup Write a script called 'parser with the following usage USMGEi parser [-h parser [-f filename] [-h] usernane There are two forms for the script. The first form simply displays the usage statement, -h is a flag for help. Unacceptable syntax or-h should display the usage statement. The second form must contain a mandatory username with an optional -h or -f argument. The script will display whether or not the username is logged on. One way to do this is to use the following command and do a comparison on the resulting count (assuming you created the username variable in your script) who grep $username we -1 When the -h option is specified, show the usage statement as above. When the -f option is specified, it must be followed by a filename. The -f option will display the number of lines in filename, if the file exists The script should allow for all optional and mandatory command line arguments to be in any order. The script must trap for the following fatal errors, display an appropriate message and exit: 1. A filename does not follow the -f switch 2· The filename passed does not exist in the current directory 3. An illegal switch is passed 4. The mandatory username is not given when the -f switch is given, even if a filename is given 5. Too many arguments are given 6. Too few arguments are given (i.e. the user does not give at least 'parser -h' or parser ') Email the script as an attachment to meExplanation / Answer
#!/bin/bash
show_help () {
echo "$0 [-h]"
echo "$0 [-h] [-f filename] username"
}
file_type () {
if [ -f "$1" ]
then
echo "$1 exists and is a regular file" > /dev/null
elif [ -d "$1" ]
then
echo "$1 exists and is a directory"
elif [ -e "$1" ]
then
echo "$1 exists but is something else"
exit -1
else
echo "$1 does not exist"
exit -1
fi
}
is_flag () {
if [[ $1 == -* || -z "$1" ]]
then
echo "Invalid argument $1"
exit 3
fi
}
is_uname () {
t=`echo $1 | grep -E '[a-z]{1,}+[0-9]{1,}+' | wc -l`
if [[ t -gt 0 ]]
then
tmp=`who | grep $1 | wc -l`
if [[ tmp -gt 0 ]]
then
echo "$1 is logged on"
#exit -1
fi
else
echo "Please enter an username"
exit -1
fi
}
if [ $# -eq 0 ]
then
echo "No arguments"
exit 1
fi
if [ $# -gt 4 ]
then
echo "Too many arguments"
exit 1
fi
while [ $# -gt 0 ]
do
case $1 in
"-h")
show_help
shift
;;
"-f")
is_flag $2
for last; do true; done
is_uname $last
file_type $2
echo "No of lines in the file"
wc -l $2 | awk ' {print $1} '
shift;shift
;;
*)
t=`echo $1 | grep -E '[a-z]{1,}+[0-9]{1,}+' | wc -l`
if [[ t -gt 0 ]]
then
echo "$1 is uname" > /dev/null
exit -1
else
echo "Unexpected argument"
exit -1
fi
;;
esac
done
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.