问题
I want to convert following bash code in pure shell script (sh) language so that it should run by other script language mode i.e dash script.
arguments=("$@")
for (( i=0; i<$#; i++ )); do
case "${arguments[$i]}" in
-foo)
let "i = i + 1"
echo "${arguments[$i]}"
;;
*)
break
esac
done
above code finely run in bash mode but through an error on dash mode.
2: ./orig.sh: Syntax error: "(" unexpected
Now If I change line 2 to get rid the error as following line
arguments="$@"
But now I got another error about loop
3: ./orig.sh: Syntax error: Bad for loop variable
回答1:
POSIX sh doesn't support arrays or C-style for loops.
i=0
while [ $(( ( i += 1 ) <= 10 )) -ne 0 ]; do
eval "val=\$$i"
case "$val" in
-foo)
i=$(( i + 1 ))
eval "val=\$$i"
echo "$val"
;;
*)
break
esac
done
回答2:
The POSIX way to handle the arguments is to consume them using shift
while $#
is non-zero.
while [ $# -gt 0 ]; do
case $1 in
-foo)
echo "$2"
shift; shift
;;
*)
break ;;
esac
done
回答3:
Now I have a Answer of my question, something like following works for me.
arguments="$@"
for i in $@; do
case "$1" in
-foo)
shift 2
echo "$1"
;;
*)
break
esac
done
来源:https://stackoverflow.com/questions/26529255/replacing-bash-arrays-and-c-style-for-loops-in-posix-sh