Question

i have a case script as follow :

 for i in "$@"; do
arg=( $@ )
    case $i in
 --string)
          for ((i=0; i<${#arg[@]}; i++)) ; do
           if [ "${arg[$i]}" == "--string" ] ; then
                ((i++))
                 STRING=${arg[$i]}
           fi
          done
          ;;
*)
          print_help
          exit
          ;;
  esac
done

when i run ./test --some_command --string pattern ; it prints the help option. When i run ./test --some_command --string pattern without the *) option in the string, it works.

Can you please tell me how to fix this.

Another example :

#!/bin/bash

test(){

        echo i am testing this now
}

print_help()
{
  echo help
}

for i in "$@"; do
arg=( $@ )
    case $i in
 --string)
          for ((i=0; i<${#arg[@]}; i++)) ; do
           if [ "${arg[$i]}" == "--string" ] ; then
                ((i++))
                 STRING=${arg[$i]}
           fi
          done
                echo $STRING
          ;;
 --test)
        test
        ;;

 *)
          print_help
          exit
          ;;
  esac
done

when i run ./test --string pattern --test. it prints pattern help

Was it helpful?

Solution

When the for loop gets to "pattern", it is not covered by a case branch so it hits the default branch and prints the help. You have to iterate over the arguments in a smarter way. Replace for for loop with

while (( $# > 0 )); do
    arg=$1
    shift
    case $arg in
        --string) STRING=$1; shift; echo "$STRING" ;;
        --some-command) : ;;
        --) break ;;
        *) print_help; exit ;;
    esac
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top