开发者

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.


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


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.


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"]}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜