在 bash 中循环参数

问题描述 投票:0回答:1

我正在尝试编写一个在我的参数列表上运行的代码, 例如,如果我有

-p a b c d -q g e f c
作为参数: 当我得到
-p
时,我希望循环在变量
a b c d
上运行,直到我得到
-q
,然后做其他事情, 同样我希望它是相反的;

这是我的代码:

#bin/bash
while test -n "$1" -a ${1:0:1} = - ;do
if test x$1=x-q:then
    shift
    while test -n "$1" ; do
        echo $1
        if test x$2=x-p;then 
            break;
        shift
    done
fi
if test x$1=x-p;then 
   echo 'print test'+$1;
   shift
fi
done

但是break似乎不起作用,有谁知道我如何实现这个?

bash loops arguments
1个回答
2
投票

考虑首先解析所有参数,然后将“-p”参数收集在一个数组中,将“-q”参数收集在另一个数组中:

p_args=() 
q_args=()
opt=""

for arg do 
    case $arg in 
        "-p") opt=p ;; 
        "-q") opt=q ;; 
           *) [[ $opt == p ]] && p_args+=("$arg")
              [[ $opt == q ]] && q_args+=("$arg")
              ;; 
    esac
done

# do stuff with "-p" args
declare -p p_args

# do stuff with "-q" args
declare -p q_args
© www.soinside.com 2019 - 2024. All rights reserved.