Bash doesn't typically care about the values of the arguments, it's more their ordering, and how they're separated on the command line, by default parsing them based on a space between each argument.
You can see this with a simple for
loop construct in a shell script like so:
#!/bin/bash
echo ""
echo "ARGS: $@"
echo ""
echo "parsed args:"
for i in "$@"; do
echo "$i"
done
Example
$ ./parse.bash -f aPHPscript.php -d memory_limit=120M -d apc=1 \
-d max_execution_time=120
ARGS: -f aPHPscript.php -d memory_limit=120M -d apc=1 -d max_execution_time=120
parsed args:
-f
aPHPscript.php
-d
memory_limit=120M
-d
apc=1
-d
max_execution_time=120
In the above, each iteration through the loop is "peeling off" the next argument that was passed into the script parse.bash
. So rather then use getopts
you could always do something like this.
Using while + case
I typically don't use getopts
and do things as you're inquiring about like so with a while
loop using a case
statement to parse the arguments as required.
$ more parse2.bash
#!/bin/bash
while [[ $# > 1 ]]
do
key="$1"
shift
# -f aPHPscript.php -d memory_limit=120M -d apc=1
#+ -d max_execution_time=120
case $key in
-f)
f_ARG="$1"
shift
;;
-d)
d_ARGS=( "${d_ARGS[@]}" "$1" )
shift
;;
*)
# unknown option
;;
esac
done
echo "$f_ARG"
echo "${d_ARGS[@]}"
When we run it with your arguments we can see that it was able to parse your -d
arguments into an array, $d_ARGS
.
$ ./parse2.bash -f aPHPscript.php -d memory_limit=120M -d apc=1 \
-d max_execution_time=120
aPHPscript.php
memory_limit=120M apc=1 max_execution_time=120
References