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?