Shailesh Yadav
Shailesh Yadav

Reputation: 301

$ is compulsory in case of conditional statement-linux [ ]?

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

Answers (1)

that other guy
that other guy

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:

  • Arithmetic expansion $((here)) and arithmetic commands ((here))
  • Integer comparators in [[ .. ]] (but not [ .. ]), such as [[ here -eq here ]]§. Note in particular that = is a string comparator.
  • Values assigned to variables declared as integers: declare -i foo=here§
  • Indices of indexed arrays: ${array[here]}
  • Arguments to let: let here§
  • Some other more niche constructs like ${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

Related Questions