0

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?

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
red888
  • 22,770
  • 38
  • 161
  • 304
  • `echo "sdf sdfsd sd =$((myvar+=1)) sdf sdf "` the equal sign before the arithmetic expansion must be added manually. @JohnKugelman – iBug Jan 28 '18 at 15:14
  • The OP doesn't want `=1`. They want `11`. – John Kugelman Jan 28 '18 at 15:38
  • really just want to increment every iteration (whether the new value is returned immediately or in the succeeding loop). += does what i want – red888 Jan 28 '18 at 15:45
  • Have a look at: https://stackoverflow.com/questions/4181703/how-to-concatenate-string-variables-in-bash/18041780#18041780 – F. Hauri Jan 28 '18 at 20:20

2 Answers2

2

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

iBug
  • 32,728
  • 7
  • 79
  • 117
0

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

Benjamin W.
  • 38,596
  • 16
  • 96
  • 104