red888
red888

Reputation: 31550

Can I evaluate expressions in the bash string interpolation?

I tried this:

aaa=10
echo "sdf sdfsd sd ${aaa+=1} sdf sdf "

And got back:

aaa=10
sdf sdfsd sd =1 sdf sdf

Does bash support doing this somehow?

Upvotes: 0

Views: 169

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52112

${parameter+word} is a special parameter expansion in Bash (also required by POSIX): it stands for "if parameter is unset, use nothing, else use the expansion of word instead".

There is a variation of the expansion with :+ instead of + that uses the expansion of word if parameter is unset or null.

These are all the possible scenarios:

$ unset myvar
$ echo "${myvar+instead}"    # Unset: print nothing

$ myvar=
$ echo "${myvar+instead}"    # Null: print "instead"
instead
$ myvar=this
$ echo "${myvar+instead}"    # Set and not null: print "instead"
instead
$ unset myvar
$ echo "${myvar:+instead}"   # Unset: print nothing

$ myvar=
$ echo "${myvar:+instead}"   # Null: PRINT NOTHING (effect of :+)

$ myvar=this
$ echo "${myvar:+instead}"   # Set and not null: print "instead"
instead

In your case, because myvar is not null, you see =1 instead.

What you want is arithmetic expansion (see iBug's answer).

In Bash, you can use prefix increment for this:

$ var=10
$ for i in {1..3}; do echo "$((++var))"; done
11
12
13

POSIX doesn't require ++ and --, though.

Upvotes: 0

iBug
iBug

Reputation: 37227

Yes. You can use $(( expression )) for arithmetic expansion:

echo "sdf sdfsd sd $((myvar+=1)) sdf sdf "
                    ^^        ^^

Output (with a preceding variable assignment myvar=0):

sdf sdfsd sd 1 sdf sdf 

The whole token $(( expression )) is expanded to the result of the expression after evaluation. So echo $((1+2)) gives 3.

There's another non-expanding version of expression evaluation, (( expr )), which returns true/false depending on the evaluation of the expression (non--zero/zero).

From man bash:

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:

$((expression))

You must use double parentheses, as single parentheses is used to capture output of a command:

a=$(echo "hahaha") # a is hahaha
a=$((1+2)) # a is 3

Thanks to @JohnKugelman for pointing out the name of the syntax and the manpage

Upvotes: 2

Related Questions