1

Just want to share with you something I did not easily find by myself...

I am a newbie in shell script and was just wondering how can I increment a value of a an associative array.

Let's assume this script:

#!/bin/bash

declare -A b # declare an associative array 

a="aaa"
b[$a]=1

echo ${b[@]} # display all the values
echo ${b[$a]} # display the first value (1)
echo ${b[aaa]} # display the first value as well (1)

The solution can be

((b[$a]++))
echo ${b[@]} # display 2

Now that I found it, it seems evident, but I spent some time to get it...

I hope this can save some time to people :)

4
  • 1
    Note, you should use quotes: (('b[$a]'++)). Commented Oct 15, 2015 at 13:47
  • @gniourf_gniourf What is the benefit of using quotes there? Commented Oct 15, 2015 at 13:54
  • @Bast, post your solution as an answer. Commented Oct 15, 2015 at 13:56
  • 1
    @999999999999999999999999999999There are a few glitches with the way Bash parses arithmetic: for example, try it with these keys: a=' ', a=@, a=*, gniourf=hello; a='$gniourf' or even better: a='hi$(ls>&2)' (and you're glad I only put a friendly command there). Surprise. Commented Oct 15, 2015 at 14:00

1 Answer 1

3

As describe above, the solution can be

((b[$a]++)) #  or (('b[$a]'++)) for a more secure way as pointed by @gniourf_gniourf
echo ${b[@]} # display 2

Now that I found it, it seems evident, but I spent some time to get it...

I hope this can save some time to people :)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.