Michael
Michael

Reputation: 42050

Double parentheses to increment a variable in bash

Suppose I increment a variable in bash. For instance,

> i=0; for f in `ls *.JPG`; do echo $f $i; ((i++)); done
a0.jpg 0
a1.jpg 1
...

Now I wonder why I need those double parentheses to increment i.

Upvotes: 2

Views: 1224

Answers (2)

Aman
Aman

Reputation: 8985

The double parentheses construct is a shell feature to support arithmetic operations. The same construct can also be used for Loops and special numerical constants.

Also, copied from the first link :

# -----------------
# Easter Egg alert!
# -----------------
#  Chet Ramey seems to have snuck a bunch of undocumented C-style
#+ constructs into Bash (actually adapted from ksh, pretty much).
#  In the Bash docs, Ramey calls (( ... )) shell arithmetic,
#+ but it goes far beyond that.
#  Sorry, Chet, the secret is out.

Upvotes: 6

Dan
Dan

Reputation: 4502

i++ is a perfectly valid file name, and if I have access to your system, I can make that into a command that does something you don't want.

Try creating a file, /bin/i++ with this content:

#!/bin/sh
echo 'Gotcha'

and then chmod +x /bin/i++

Upvotes: 4

Related Questions