2

I'm writing a shell, others can pass arguments to it, like:

someshell task1 task2 -Daaa=111 -Dbbb=222 task3

In the shell, I can get all the arguments with $@, which is:

task1 task2 -Daaa=111 -Dbbb=222 task3

Then I want to get all args start with -D out of the string, and make two strings:

-Daaa=111 -Dbbb=222

and

task1 task2 task3

I'm not familiar with bash, what I can do now is to split the string and check each item, then group them in someway. Which seems a little complex.

If there is any simple way to do this?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • [getopt might be able to help you.](https://stackoverflow.com/questions/20262143/shell-script-parameters) Perhaps this is a duplicate? – Cel Skeggs Jun 30 '15 at 03:46
  • @col6y 'getopt' is not applicable for my case. I don't need parsing more options, just want to split `-D` with others – Freewind Jun 30 '15 at 05:13
  • See http://mywiki.wooledge.org/BashFAQ/035 for some useful ways to handle command line arguments. – Etan Reisner Jun 30 '15 at 12:57

1 Answers1

4

One approach is:

#!/bin/bash

for i in "$@"; do
    [ ${i:0:2} = -D ] && ar1+=( $i ) || ar2+=( $i )
done

echo "string1: ${ar1[@]}"
echo "string2: ${ar2[@]}"

Output

$ bash myarg.sh task1 task2 -Daaa=111 -Dbbb=222 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3

Another option:

for i in "$@"; do
    [[ $i = -D* ]] && ar1+=( $i ) || ar2+=( $i )
done

Full example:

#!/bin/bash

for i in "$@"; do
    [ ${i:0:2} = -D ] && ar1+=( $i ) || ar2+=( $i )
done

echo "string1: ${ar1[@]}"
echo "string2: ${ar2[@]}"

unset ar1
unset ar2

for i in "$@"; do
    [[ $i = -D* ]] && ar1+=( $i ) || ar2+=( $i )
done

echo "string1: ${ar1[@]}"
echo "string2: ${ar2[@]}"

exit 0

Output

$ bash myarg.sh task1 task2 -Daaa=111 -Dbbb=222 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3
string1: -Daaa=111 -Dbbb=222
string2: task1 task2 task3
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85