BASH: basic, if then variable assignment

I'm used to csh, so this annoys the need to use bash. What is wrong with this code?

if[$time > 0300] && [$time < 0900] then $mod=2 else $mod=0 fi 
+6
source share
1 answer

According to the 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 check the values. There are no arithmetic-like comparison operators like > and < in [ ] , only -lt , -le , -gt , -ge , -eq and -ne .

When you are in bash, [[ ]] is preferable since variables are not subject to splitting and path extension. You also do not need to extend the $ variables for arithmetic comparisons.

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

Also, using (( )) for arithmetic comparisons may be best for your preferences:

 if (( time > 300 && time < 900 )) then mod=2 else mod=0 fi 
+11
source

Source: https://habr.com/ru/post/954012/


All Articles