Kim
Kim

Reputation: 211

Variable in shell script

#!/bin/bash
i=1
until [ $i -gt 6 ]
do
    echo "Welcome $i times."
    i=$(( i+1 ))
done

Why we use double () in i=$(( i+1 )),and why if we change the program to

i=$( i+1 )

or

i++

or

$i=$i+1

, it is not correct?

Upvotes: 2

Views: 257

Answers (2)

jrn.ak
jrn.ak

Reputation: 36619

http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/dblparens.html

Similar to the let command, the ((...)) construct permits arithmetic expansion and evaluation. In its simplest form, a=$(( 5 + 3 )) would set "a" to "5 + 3", or 8. However, this double parentheses construct is also a mechanism for allowing C-type manipulation of variables in Bash.

Upvotes: 1

sepp2k
sepp2k

Reputation: 370162

$( foo ) tries to execute foo as a command in a subshell and returns the result as a string. Since i+1 is not a valid shell command, this does not work.

$(( foo )) evaluates foo as an arithmetic expression.

It's just two similar (but different) syntaxes that do different things.

Upvotes: 3

Related Questions