0

Let's say I have a bash script that takes in some arguments. e.g.,

some_script.sh --flag1 --flag2 --flag3

Now let's say I want to only pass in flag1 and flag2. However, I have a string, "--flag1 --flag2". What I want to do is this:

some_script.sh --flag1 --flag2

but I'm having trouble converting that string to inputs. If I do this,

some_script.sh "--flag1 --flag2"

my bash script does not parse the flags correctly, as it thinks I'm passing in an invalid argument (since the argument is one long string, technically).

I've tried using a list, like so:

some_script.sh ["--flag1", "--flag2"]

then iterating through the list in my bash script, but no luck. Here is my sample bash script:

while (( $# > 0 ))
do
    opt="$1"
    shift

    case $opt in

    --flag1)
        var1=true
        ;;
    --flag2)
        var2=true
        ;;
    --flag3)
        var3=true
        ;;
    --*)
        echo "One or more arguments is not valid"
        exit 1
        ;;
    *)  
        break
        ;;
   esac

done

How could I iterate through a string of arguments during this while loop? Basically, how would I iterate through the "--flag1 --flag2" string or at least iterate through an array, ["--flag1", "--flag2"]? It seems like perhaps I need to change the following line:

while (( $# > 0 ))

but I've tried using $[@] for an array input, in place of $#, and I'm not getting a correctly parsed string. I've also tried iterating through a list using a for loop to iterate through items that way, but no luck. I can split a string using set or IFS, but that seems a bit complicated for a command line tool. Surely there is an easier way to split and iterate during the while loop?

user42390
  • 491
  • 1
  • 5
  • 9
  • 3
    What was the problem with doing `some_script.sh --flag1 --flag2`? – kabanus Aug 26 '18 at 20:40
  • 3
    This whole thing smells like an XY problem. How are you running this bash script? – melpomene Aug 26 '18 at 20:40
  • 3
    `["--flag1", "--flag2"]` is not an array. That's not how bash works. – melpomene Aug 26 '18 at 20:41
  • 2
    Wild stab in the dark based on your 2 most recent questions - are you trying to call this shell script from python and so have some complexity around how to do that and THAT is what your question is actually about? If so then provide a [mcve] that includes the context for how you're calling the shell script and tag your question with python. – Ed Morton Aug 26 '18 at 20:46

0 Answers0