Replacing bash arrays and C-style for loops in POSIX sh

99封情书 提交于 2019-12-10 12:37:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!