0

Given the following code:

Max=
if [[ something exists.. ]]; then
     Max=2
// .. more code that can changes the value of Max
fi
// HERE

How can I check at "HERE" if Max is equal to some number (setted)?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Software_t
  • 576
  • 1
  • 4
  • 13

2 Answers2

0

Cool !

Max is set by default to an empty value, that when used in an arithmetic context, returns zero. For example:

Try running echo $(( definitelyNotAGivenName)) it comes out as zero, cool!

You can use the round brackets for arithmetic comparing - see more here and here

AlphaBeta
  • 65
  • 1
  • 10
0
if [ -z "$Max" ]
then
  echo "Max: not set"
else if [ $Max -eq some_number ]
then
  echo "Max is equal to some number"
else
  echo "Max is set but not equal to some number"
fi

or

if [ -n "$Max" -a "$Max" = "some_number" ]
...

Notice that the second example is doing a string comparison which can solve some headaches but may hurt the sensibilities of purists.

keithpjolley
  • 2,089
  • 1
  • 17
  • 20
  • Note that `-a` is marked obsolescent in the POSIX test standard; see the `OB` markers in http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html – Charles Duffy Jul 05 '18 at 16:40
  • Also, `=` is a string comparator, perhaps you want `-eq`. Is it okay for `5` to be different from `05`? – ghoti Jul 05 '18 at 16:42
  • I found the purist. :) – keithpjolley Jul 05 '18 at 16:44
  • @ghoti - `=` is on purpose to guard against something like `Max=five`. I assumed `some_number` is hardcoded into the script, not user input. – keithpjolley Jul 05 '18 at 16:48
  • Sometimes it matters -- `test` uses that allow logical ANDs, ORs and parenthesis to control order-of-operations are obsolescent for good reason. Consider if `a='('` and `b=')'`; is `[ "$a" = "$b" ]` asking if `(` and `)` are the same character (false!), or is it a grouping operation testing whether `=` is a non-empty string (true!)? That particular corner case is a simple one, for ease of explanation, but nastier variants exist. `[[ ]]` doesn't have the problem -- being syntax, it knows which words were expanded from variables and which were part of the expression. – Charles Duffy Jul 05 '18 at 16:48