Question: Shell Scripts (Linux) Code so far (bottom of page): Write a script called 'parser' with the following usage: USAGE: parser [-h] parser [-f filename] [-h]
Shell Scripts (Linux)
Code so far (bottom of page):
Write a script called 'parser' with the following usage:
| USAGE: | parser [-h] |
| parser [-f filename] [-h] username |
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 | wc -l
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
Code so far:
#!/bin/bash
show_help () { echo "$0 [-h]" echo "$0 [-h] [-u username] [-f filename]" } user_proc () { num=$(ps -u $1 | wc -l) echo "user $1 owns $num processes" } file_type () { if [ -f "$1" ] then echo "$1 exists and is a regular file" elif [ -d "$1" ] then echo "$1 exists and is a directory" elif [ -e "$1" ] then echo "$1 exists but is something else" else echo "$1 does not exist" fi } is_flag () { if [[ $1 == -* || -z "$1" ]] then echo "Invalid argument $1" exit 3 fi }
if [ $# -eq 0 ] then show_help exit 1 fi
while [ $# -gt 0 ] do case $1 in "-h") show_help shift ;; "-f") is_flag $2 file_type $2 shift;shift ;; "-u") is_flag $2 user_proc $2 shift 2 ;; *) echo "Unexpected argument" exit 2 ;; esac done
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
