2

I need to send an email only if a condition is reached, but I'm having error running this script:

file='/somewhere/here/file.txt'
value=$(cat "$file")
if [$value < 99]; then
     echo "$value" | mailx -s "title"  [email protected]
fi

the error I'm getting is this:

[line 4: 99]: No such file or directory

file rights: 0755

file '/somewhere/here/file.txt' is present

Noomak
  • 279
  • 2
  • 4
  • 5
  • 3
    Possible duplicate of [Why are bash tests so picky about whitespace?](https://unix.stackexchange.com/questions/117438/why-are-bash-tests-so-picky-about-whitespace) – Inian Sep 13 '19 at 10:41
  • @Inian not quite. The `<` is for input redirection, not for comparison, so that won't work either. – terdon Sep 13 '19 at 10:49
  • 2
    Try https://shellcheck.net/ for these kind of errors. – roaima Sep 13 '19 at 11:05

1 Answers1

4

Remember that each programming language has its own syntax and you really should read the relevant documentation before trying to use a new language. In the shell, < doesn't mean "smaller than", it means "take this file as input". To do a numerical comparison, you want -lt for "less than".

In addition, you always need spaces around the [ and ]. So what you wanted to write is something like:

if [ "$value" -lt 99 ]; then
     echo "$value" | mailx -s "title"  [email protected]
fi

For more details, please see help test and man bash.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
terdon
  • 234,489
  • 66
  • 447
  • 667