I want to write a shell script which will take some arguments with some options and print that arguments. Suppose the name of that script is abc.ksh
. Usage of that script is -
./abc.ksh -[a <arg>|b <arg>|c|d] <some_string>
Now I write a shell script which will take options and arguments
#!/bin/ksh
# Default Values
vara=","
varb=false
varbname=""
varc=false
# Scanning inputs
while getopts :a:b:cd option
do
case $option in
a) vara=$OPTARG;;
#shift $((OPTIND-1));;
b) varb=true
varbname=$OPTARG;;
#shift $((OPTIND-1));;
c) varc=true;;
#shift $((OPTIND-1));;
d) echo "Usage $0 \-[a|b|c|d] <filename>"
exit 0;;
\?) echo "Invalid option -$OPTARG. Please run '$0 -h' for help"
exit 1;;
:) echo "Option -$OPTARG requires an argument. Please run '$0 -d' for help"
exit 1;;
esac
done
print "Args: $* \nvara: $vara \noptfile: $varb \nvarbname: $varbname \nvarc: $varc"
Examples of Correct Inputs:
./abc.ksh -a "sample text" "some_string"
./abc.ksh "some_string" -a "sample text"
./abc.ksh -asample\ text some_string
- etc...
some_string
input is not catch in my script. How can I catch that?
Getopt::Long
will extract the options and leave the non-option arguments in @ARGV.getopt
?man getopt
I've only used getopt in C so I can't really say exactly what the code should look like, but it seems like better than implementing getopt yourself.