user7310293
user7310293

Reputation:

How do I subtract 1 from an array item in BASH?

I have a side-project in BASH for fun, and I have this code snippet (ARRAY[0] is 8):

while [ $ALIVE == true ]; do
    $ARRAY[0] = ${ARRAY[0]} - 1
    echo ${ARRAY[0]}
done

However, it comes back with this error:

line 16: 8[1]: command not found

I just started working in BASH, so I might be making an obvious mistake, but I've searched and searched for an answer to a problem like this and came up with no result.

Upvotes: 0

Views: 5346

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295629

The smallest change is simply:

ARRAY[0]=$(( ${ARRAY[0]} - 1 ))

Note:

  • No $ before the name of the variable to assign to (foo=, not $foo=)
  • No spaces around the = on the assignment
  • $(( )) is the syntax to enter a math context (and expand to the result of that operation).

Upvotes: 2

Related Questions