views:

52

answers:

3

Hello All,

Let's say i have the Following,

Vegetable=Potato ( Kind of vegetable that i have )

Potato=3 ( quantity available )

If i wanna know how many vegetables i have (from a script where i have access only to variable Vegetable), i 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)

It does not work !!

Any clues to realize this

Thanks

+2  A: 
eval ${Vegetable}=$(expr ${!Vegetable} - 1) 
Dave Bacher
A: 

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"]}
ghostdog74
+2  A: 

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.

Dennis Williamson
Ah, thanks! `eval` is a hack in this situation.
Dave Bacher