1

my if condition with gt compare value and also if the value is null, but I want that gt compare null value, I just want that he compare only value

 res=''
 toto=5
 if [[  "$toto" -gt "$res"  ]]; then
    ... 
   else
    ...
   fi
 fi

solution is that, but not very good

 if [[ ! -z "$res"  ]]; then
   if [[  "$toto" -gt "$res"  ]]; then
     ... 
   else
     ...
   fi
 fi
4
  • What should happen if res is null? Is that an error condition, or does it just not execute that code path? Commented Mar 28, 2019 at 18:08
  • if res is null, he jump to another section and continue read the code Commented Mar 28, 2019 at 18:11
  • not execute code path Commented Mar 28, 2019 at 18:11
  • If your code is structured with functions, you could return early from that function. Otherwise, what you have is just about as good as it gets (aside from -n vs ! -z) Commented Mar 28, 2019 at 18:17

2 Answers 2

1

Use &&.

if [[ ! -z "$res" && "$toto" -gt "$res" ]]

Other improvements you could make:

  • Replace ! -z with -n.
  • Remove unnecessary quotes.
  • Use ((...)) for numerical comparisons.
if [[ -n $res ]] && ((toto > res))
Sign up to request clarification or add additional context in comments.

2 Comments

nope, because, for else statement he would be considered comparison value betwen null and $toto, so he must'nt do comparaison because, $res is null
so I don't want that -gt compare value if res='' I want only compare if there is a number not a null value
0

This Shellcheck-clean code handles empty $res in another way:

#! /bin/bash

res=''
toto=5
if [[ -z $res ]] ; then
    : # $res is empty so don't compare with $toto
elif ((  toto > res )); then
    echo 'toto is greater than res'
else
    echo 'toto is less than or equal to res'
fi

However, it's debatable whether it's better or worse than the "not very good" option suggested in the question. Deeper nesting is usually worse, but if-the-else chains are best avoided. The only advantage I would claim for the code in this answer is that it has a convenient place to put a helpful comment if one is useful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.