Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command line arguments in Bash [duplicate]

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?

like image 503
Pascal Avatar asked Aug 20 '12 10:08

Pascal


2 Answers

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, ...

like image 94
tzelleke Avatar answered Oct 19 '22 07:10

tzelleke


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 
like image 32
Jo So Avatar answered Oct 19 '22 07:10

Jo So