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?
2 Answers 2
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,ドル ...
codeforester
43.8k21 gold badges123 silver badges159 bronze badges
answered Aug 20, 2012 at 11:08
tzelleke
15.4k5 gold badges35 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Federico
mywiki.wooledge.org/BashFAQ/035 "getopt cannot handle empty arguments strings, or arguments with embedded whitespace. Please forget that it ever existed."
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
answered Aug 20, 2012 at 11:07
Jo So
26.9k6 gold badges46 silver badges60 bronze badges
4 Comments
Steven Mackenzie
-1, far better to use getopts
Charles Duffy
@StevenMackenzie, ...I'm not sure I can agree. If you look at BashFAQ #35, the manual-parsing example (of which this is further simplification) does rather a number of things that getopts simply can't. Following the practice is thus more flexible.
Charles Duffy
@StevenMackenzie, ...we're also in a world where folks have been spoiled by GNUisms such as being able to mix optional and positional arguments (barring the use of
-- to explicitly signal end of the former and beginning of the latter alone). It's easy to do something like args+=( "1ドル" ) in a default case with a parser of this kind; with getopts, the cutoff at OPTIND is hard-and-fast.Brian Agnew
Bash FAQ 35 (as above) tells me everything I need to know
lang-bash
. myProgram -p2 -l 5 -t 20), the variables you set will only exist inmyProgram, not the shell from which you call it.