Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: Basic if then and variable assignment

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
like image 217
Corepuncher Avatar asked Sep 17 '13 17:09

Corepuncher


People also ask

Can you assign variables in bash?

A variable in bash is created by assigning a value to its reference. Although the built-in declare statement does not need to be used to explicitly declare a variable in bash, the command is often employed for more advanced variable management tasks.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is bash if [- N?

A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.

How do you assign a value to a variable in a shell script using IF statement?

This will work: x = $(if [ 2 = 2 ]; then echo equal; else echo "not equal; fi) .


1 Answers

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
like image 198
konsolebox Avatar answered Oct 15 '22 01:10

konsolebox