Search code examples
bashloopsarguments

Looping through arguments in bash


I'm trying to write a code that runs on my arguments list , for example if I have -p a b c d -q g e f c as arguments: when I get -p, I want the loop to run on variables a b c d, until I get -q, and then to do something else, likewise I want it to be in reverse;

this is my code:

#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

but break doesn't seem to work, does anyone know how I can implement this?


Solution

  • Consider first parsing all the arguments, and collection the "-p" args in one array and the "-q" args in another array:

    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