0

I would like to update a script that is currently like this:

$ example.sh a b

Here is the code within example.sh

for var in "$@"
do
    $var
done

Where it takes in arguments and those arguments are looped over and executed (assuming those arguments exist).

I would like to update the script so that these flags are the scripts / functions and that everything after is applied as the argument to the function.

$ example.sh --a 1 2 3 --b 4 5 6

I would like to loop over all flags and run the equivalent of.

a 1 2 3
b 1 2 3

I have looked into getopts but I am not sure if it will allow me to execute and pass in the arguments the way I would like.

What I tried:

while getopts ":a:b:c:d:" opt; do
  case "$opt" in
    a) i=$OPTARG ;;
    b) j=$OPTARG ;;
    c) k=$OPTARG ;;
    d) l=$OPTARG ;;
  esac
done

echo $i
echo $j

for file in "$@"; do
  echo $file
done

I found the following script which given example --a 1 2 3 --b 4 5 6 will only assign the first item using OPTARG and it doesn't work properly. I am unsure how to apply arguments to a function in this format.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

2 Answers2

1

I don't know of any automatic way to do what you want, but you can just loop through your arguments and construct your commands, like this:

#!/bin/bash

cmd=()
while [ $# -gt 0 ]; do                         # loop until no args left
    if [[ $1 = --* ]]; then                    # arg starts with --
        [[ ${#cmd[@]} -gt 0 ]] && "${cmd[@]}"  # execute previous command
        cmd=( "${1#--}" )                      # start new array
    else
        cmd+=( "$1" )                          # append to command
    fi
    shift                                      # remove $1, $2 goes to $1, etc.
done

[[ ${#cmd[@]} -gt 0 ]] && "${cmd[@]}"          # run last command
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
-1

Perhaps this way.

cat example.sh

while read line;do
  $line
done <<<$(echo $@ | sed 's/--/\n/g')

and I try that

./example.sh '--echo 1 2 3 --dc -e 4sili5+p'

output

1 2 3
9
ctac_
  • 2,413
  • 2
  • 7
  • 17