Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you need a dollar symbol before an arithmetic statement in bash?

Tags:

bash

I am trying to get my head around bash but am struggling with some core foundations.

I can see an arithmetic statement is defined by double parentheses

((5-3))

but if I try to echo that or us it in shift I get an error

echo ((5-3))
-bash: syntax error near unexpected token `('

In examples it shows that prefixing it with a dollar symbol will make it work

echo $((5-3))

Why is that? The syntax looks as though I'm applying the arithmetic to a blank variable and then onto the echo function. Why can't I just pass the result of the arithmetic into the echo function? How do I know when to prefix an arithmetic statement with a dollar symbol in other instances.

Please excuse my ignorance. Im so used to web development languages and Bash is just so different.

like image 850
McShaman Avatar asked Mar 18 '23 16:03

McShaman


1 Answers

((...)) is an arithmetic expression.

$((...)) is an arithmetic expansion.

The difference is that an expression is a unit on its own but an expansion just gets replaced with a value.

This is the same thing as the difference between.

$ echo foo
foo

and

$ $(echo foo)
-bash: foo: command not found
like image 184
Etan Reisner Avatar answered May 08 '23 21:05

Etan Reisner