2
#!/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?

2
  • I've moved this to stackoverflow as this is not a request for people to review your code. Commented Mar 1, 2011 at 17:45
  • You can also do ((i++)), ((i += 1)) or ((i = i + 1)). Commented Mar 1, 2011 at 18:30

2 Answers 2

3

$( 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.