2

Say I have an array arr and an index x. How do I assign something to the array at index x+1? I'm getting bugs by trying the following, if one of them is correct I'd love to know which one and if not what am I doing wrong?

arr[$x+1]="hi"      # Doesn't work
arr[$((x+1))]="hi"  # Nope
2
  • 1
    Both work correctly. GNU Bash 4.2.37(1). Commented Dec 24, 2013 at 15:12
  • References: The Bash guide for beginners says an array index "is treated as an arithmetic expression that must evaluate to a positive number." Arithmetic expressions are whatever can go inside $(( )). Commented May 19, 2018 at 12:53

1 Answer 1

4

Almost there.

arr[(($x+1))]="hi"
Sign up to request clarification or add additional context in comments.

6 Comments

So why would I be getting this: ./win.bash: line 114: syntax error near unexpected token (' ./win.bash: line 114: let game[(($j+1))]=$tmp'
You're not using bash as your interpreter. Or you're using an old version.
bash --version: v 4.1.2(1)
x is neither a number nor a variable.
x isn't a variable? It's my loop index... for (( x=0; x<total; x+=2 )) And about the version problem, nevermind... I found out x is empty when the bug is reached
|

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.