I want to write a bash script which takes different arguments. It should be used like normal linux console programs:
my_bash_script -p 2 -l 5 -t 20
So the value 2 should be saved in a variable called pages and the parameter l should be saved in a variable called length and the value 20 should be saved in a variable time.
What is the best way to do this?
Use the getopts
builtin:
here's a tutorial
pages= length= time= while getopts p:l:t: opt; do case $opt in p) pages=$OPTARG ;; l) length=$OPTARG ;; t) time=$OPTARG ;; esac done shift $((OPTIND - 1))
shift $((OPTIND - 1))
shifts the command line parameters so that you can access possible arguments to your script, i.e. $1, $2, ...
Something along the lines of
pages= length= time= while test $# -gt 0 do case $1 in -p) pages=$2 shift ;; -l) length=$2 shift ;; -t) time=$2 shift ;; *) echo >&2 "Invalid argument: $1" ;; esac shift done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With