0

I have a script that I'm writing and I've set some flags using If statements. for example my flags are set as

flag=$(-a,-b,-c,-d)

and for example my If statement is set as

if echo "$flag" | grep -q -E -o "(-)(a)"; then
        1
fi

my question is how do I add another if statement that will say if flag does not exist, then show an error. I've tried something like the following but it does not work.

if "[[ $flag"=="*" ]]; then
        Error.
fi

Any suggestions? Thanks!

DevSolar
  • 67,862
  • 21
  • 134
  • 209
  • Does `flag=$(-a,-b,-c,-d)` really work? Do you mean `flag=(-a,-b,-c,-d)`? – md2perpe Feb 14 '22 at 18:27
  • @md2perpe yeah sorry the $ sign was a typo.. the main thing though is how to write if someone entered -k for example and it will notify him its a wrong input. – Benjamin Abergel Feb 14 '22 at 18:30
  • I removed the tag "flags" because your issue just happens to be with a variable *named* "flags", not flags *per se*. I also removed the "Linux" tag because bash is not just on Linux. – DevSolar Feb 14 '22 at 18:32
  • @DevSolar Okay thanks! I'm a bit new to bash scripting so thanks for the assistance with the tags :) – Benjamin Abergel Feb 14 '22 at 18:41

2 Answers2

0

"If flag does not exist" -- like, flag not being defined?

You could treat all undefined variables as errors.

Or you could check if the variable is set.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
0

bash suggests a solution with its own $- variable.

Store each flag as a single character in a string:

flags="abcd"

then use pattern-matching to determine if a particular flag is set or not:

if [[ $flags = *a* ]]; then
    echo "a is set"
else
    echo "a is not set"
fi
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks for the answer. I'm only using If for each flag so I'll be able to use several flags together. When I've used If-elif-else it only takes the first flag that was set. – Benjamin Abergel Feb 14 '22 at 18:54