开发者

How to change the value of value in BASH?

开发者 https://www.devze.com 2022-12-24 05:55 出处:网络
Let\'开发者_开发问答s say I have the following: Vegetable=Potato ( Kind of vegetable that i have )

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

精彩评论

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

关注公众号