20

I'm used to csh, so this is kinda irritating having to use bash. What is wrong with this code?

if[$time > 0300] && [$time < 0900]
then
$mod=2
else
$mod=0
fi
Corepuncher
  • 375
  • 2
  • 4
  • 15

1 Answers1

36

By standard it should be

if [ "$time" -gt 300 ] && [ "$time" -lt 900 ]
then
   mod=2
else
   mod=0
fi

In normal shell scripts you use [ and ] to test values. There are no arithmetic-like comparison operators like > and < in [ ], only -lt, -le, -gt, -ge, -eq and -ne.

When you're in bash, [[ ]] is preferred since variables are not subject to splitting and pathname expansion. You also don't need to expand your variables with $ for arithmetic comparisons.

if [[ time -gt 300 && time -lt 900 ]]
then
   mod=2
else
   mod=0
fi

Also, using (( )) for arithmetic comparisons could be best for your preference:

if (( time > 300 && time < 900 ))
then
   mod=2
else
   mod=0
fi
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • Thanks. Crazy sensitive this bash is. I typed what you had, and got erors like ./read.sh: line 14: =0: command not found But when I copy and pasted your code directly, it worked. Do you have to always indent 3 spaces before "mod=2" ? – Corepuncher Sep 17 '13 at 17:54
  • 2
    @Corepuncher It's not necessary. Indent style is anyone's option in shell scripting. I think you tried to add `$` to `mod` when assigning a value to it? `$mod=0`. In bash it would be interpreted as an expansion of `$mod` which is an empty string plus `=0`. – konsolebox Sep 17 '13 at 18:06
  • 3
    Bash needs to be sensitive about whitespace because something like `FOO= bar` is interpreted as running the command `bar` in an environment where `FOO` is set to the empty string. – chepner Sep 17 '13 at 18:11
  • will mod exist outside the scope of the if , if it hasn't been declared before? – Mehdi Oct 17 '22 at 16:34
  • @Mehdi Yes it will. – konsolebox Oct 18 '22 at 18:09