Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

bash: get only double dash or single dash options

In a linux bash script I want to have two lists of arguments, one are those started with single dash and the other those started with double dash

   example -a 1 --b=3 -c 7 --d=8

then it can return them in two group variables

  group1 : -a 1 -c 7
  group2 : --b=3 --d=8

I know that $@ holds a list of all arguments, don’t know whether I should iterate them and make them distinct or there are easier solutions. This is my try:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

g1=""
g2=""
for i in $@; do
   echo $i
   if [[ $i == --* ]]; then
      g1="${g1} $i"
   else
      g2="${g2} $i"
   fi 
done
echo $g1
echo $g2

regardless of its accuracy, it says:

test.sh: 5: [[: not found

>Solution :

Use a case/esac to facilitate the option parsing instead of a ìf. And use the shebang (#!) to choose the shell you want to use:

#!/bin/sh

g1=""
g2=""
for i in $@; do
   echo $i
   case $i in
       --*) g1="${g1} $i";;
       *) g2="${g2} $i";;
   esac 
done
echo $g1
echo $g2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading