Home > Mobile >  Grep not acting as expected, expression resolves correctly in bash conditional check for input 10-10
Grep not acting as expected, expression resolves correctly in bash conditional check for input 10-10

Time:12-01

I have this conditional running in a script:

if [[ $(df -h /data --output=pcent | tail -1 | grep -o -E [0-9] ) > 60 ]]; then echo "Not enough space on box";  else echo "Enough space on box"; fi

The check is supposed to bring up the disk free output, validate the mount /data has more than >40% free, and print out the result of the check. This works for all but the cases I list below. I believe the problem lies in the usage of grep (GNU 2.20) or the comparison to 60 but I can't understand how it fails considering it works for (some) single digit entries, and all double digits.

Running the following in a CentOS 7 box:

if [[ $(df -h /data --output=pcent | tail -1 | grep -o -E [0-9] ) > 60 ]]; then echo "Not enough space on box";  else echo "Enough space on box"; fi

(The output of df -h /data --output=pcent is a number and %, i.e. "X%") When running tests such as

if [[ $(echo 100% | tail -1 | grep -o -E [0-9] ) > 60 ]]; then echo "Not enough space on box";  else echo "Enough space on box"; fi
if [[ $(echo 100% | tail -1 | grep -o -E [0-9]*) > 60 ]]; then echo "Not enough space on box";  else echo "Enough space on box"; fi

the expected output is "Not enough space on box", however it is "Enough space on box", and running:

if [[ $(echo 7% | tail -1 | grep -o -E [0-9] ) > 60 ]]; then echo "Not enough space on box";  else echo "Enough space on box"; fi

the expected output is "Enough space on box", however the output is "Not enough space on box".

CodePudding user response:

It's doing a string comparison. 7 is greater than 6. Use mathematic evaluation with ((...)) instead of [[...]].

$: if [[ $(echo 7% | tail -1 | grep -o -E [0-9] ) > 60 ]]; then echo "Not enough space on box";  else echo "Enough space on box"; fi
Not enough space on box

$: if (( $(echo 7% | tail -1 | grep -o -E [0-9] ) > 60 )); then echo "Not enough space on box";  else echo "Enough space on box"; fi
Enough space on box

You could also do something like this -

$: not=( '' "Not " )

$: echo "${not[$(echo 7% | tail -1 | grep -o -E [0-9] ) > 60]}enough space on box"
enough space on box

$: echo "${not[$(echo 70% | tail -1 | grep -o -E [0-9] ) > 60]}enough space on box"
Not enough space on box
  • Related