Reputation: 301
I have one doubt I have started learning Linux and learn about the way we can perform mathematical operations. for example
a) using expr
> $
and space
are mandatory.
example: sum= expr $a + $b
b) using let
keyword > $
is optional but we should use space
.
c) using (())
> both $
and space
is optional.
d) using [ ]
> both $
and space
is optional.
so now I have written one simple if
statement.
#! /bin/bash
read -p "Please enter username:" name
if [ name = sunny ]
then
echo "hello Sunny is available. "
fi
echo "Sunny is busy-remaining line code"
So inside a square bracket, I am doing arithmetic operation right so why here do I need to use the $
symbol to get the name value.
Note If I'll use if [ $name = sunny ]
I'm getting expected result.
Any help/suggestion on this would be highly appreciated.
Upvotes: 1
Views: 61
Reputation: 123550
The rule is relatively simple: $
and spaces are optional in arithmetic context, but not in string contexts.
This is because if you expect a number and see foo
, you can safely assume that it must be a variable because it sure isn't a number. This is not possible for strings.
Arithmetic context includes:
$((here))
and arithmetic commands ((here))
[[ .. ]]
(but not [ .. ]
), such as [[ here -eq here ]]
§. Note in particular that =
is a string comparator.declare -i foo=here
§${array[here]}
let
: let here
§${str:here:here}
, $[here]
In your case, you are using the test
command aka [
, which (mostly) does not treat anything as an arithmetic expression. This is why you need the $
to differentiate between the literal string name
and the value of the variable name
.
§ These words are delimited by spaces so one would terminate the expression, but this does not change the fact that spaces are optional. They just need to be escaped to be considered part of the expression.
Upvotes: 2