on parsing arguments in shell

While most programming languages are accepting arguments as an array of strings, shell doesn’t


int main(int argc, char **argv) {
int i;
for (i=1; argc>i; i++)

$ make arglist
cc arglist.c -o arglist
$ ./arglist one two three four

To do the same in shell, it requires some dynamic evaluation, for instance with eval

while [ $i -le $# ]
eval ARGV[$i]=\$$i
echo "\$$i=$(eval echo \"\${ARGV[$i]}\")"

$ ./ one two three four

To further send the arguments to another script or function, it is important to take consideration of white spaces and file expansion (e.g.: *.*), this is achieved with double-quotes and the at-sign

f "${ARGV[@]}"

I recommend against using eval whenever possible. While less awesome, I would prefer something more verbose and without eval

[ -n "$1" ] && echo "\$1=$1"
[ -n "$2" ] && echo "\$2=$2"
[ -n "$3" ] && echo "\$3=$3"
[ -n "$4" ] && echo "\$4=$4"
[ -n "$5" ] && echo "\$5=$5"

$ ./ one two three four

Using eval is difficult and dangerous. The innocent may messed up with the quotes resulting in random effects. It is also a common source of code injection

eval x=$1

$ ./ 1
$ ./ "1; echo uh-oh"

Ref: Eval Injection