Debugger
Debugger

Reputation: 9488

How to change the value of value in BASH?

Let's say I have the following:

Vegetable=Potato ( Kind of vegetable that i have )
Potato=3 ( quantity available )

If I want to know how many vegetables I have (from a script where I have access only to variable Vegetable), I would do the following:

Quantity=${!Vegetable}  

But let's say I take one Potato then I want to update the quantity, I should be able to do the following:

${Vegetable}=$(expr ${!Vegetable} - 1)  

However, this doesn't work. Could someone please explain why.

Upvotes: 0

Views: 214

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 360105

Try:

declare $Vegetable=$((${!Vegetable} - 1))

You don't need to use expr, by the way. As you can see, Bash can handle integer arithmetic.

See this page for more information on indirection in Bash.

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342373

with bash 4.0 you can make use of associative arrays

declare -A VEGETABLE
VEGETABLE["Potato"]=3
VEGETABLE["Potato"]=$((VEGETABLE["Potato"]-1))
echo ${VEGETABLE["Potato"]}

Upvotes: 0

Dave Bacher
Dave Bacher

Reputation: 15972

eval ${Vegetable}=$(expr ${!Vegetable} - 1) 

Upvotes: 2

Related Questions