繁体   English   中英

在bash中循环遍历参数

[英]Looping through arguments in bash

我正在尝试编写在参数列表上运行的代码,例如,如果我将-pabcd -qgefc作为参数:当我得到-p ,我希望循环在变量abcd上运行,直到得到-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

但是中断似乎没有用,有人知道我该如何实现吗?

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

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 "-p" args
declare -p q_args

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM