I want to write a bash script :
schedsim.sh [-h] [-c x] -i pathfile
Where :
• -h: print the current username.
• -c x : get an option-argument x and print out (x + 1). If no argument was found, print the default value is 1.
• -i pathfile: print the size of pathfile. The pathfile is a required argument. If no argument was found, print out an error message.
This is what I've done so far :
x=""
path=""
while getopts ":hc:i:" Option
do
case $Option in
h) echo -e "$USER\n"
;;
c) x=$optarg+1
;;
i) path=$(wc -c <"$optarg")
;;
esac
done
if [ -z "$x"]
then
echo -e "$x\n"
else
echo 1
fi
if [ -z "$path"]
then
echo $path
else
echo "Error Message"
exit 1
fi
How to finish the option-argument,required-argument part and the error message part?
I think what you're looking for is "argument parsing" in bash. Please take a look at this excellent answer: https://stackoverflow.com/a/14203146/3380671
Regarding this required/optional part: initialize the variable with an empty string and just check the string's length after the argument parsing.
A rewrite:
Notes:
OPTARG
must be in upper case.$((...))
for bash arithmeticpath
does not represent the size of a file)]
echo -e "value\n"
is too much work: you just wantecho "value"
unless you want to process escape sequences in the value:Update: responding to comments: simplified and more complete option handling; expanded error handling.