代码之家  ›  专栏  ›  技术社区  ›  Debugger

如何改变bash中的值?

  •  0
  • Debugger  · 技术社区  · 16 年前

    假设我有以下几点:

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

    如果我想知道我有多少蔬菜(从我只能访问变量的脚本中) Vegetable ,我将执行以下操作:

    Quantity=${!Vegetable}  
    

    但是我要一个 Potato 然后,我想更新数量,我应该能够做到以下几点:

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

    但是,这不起作用。有人能解释一下为什么吗?

    3 回复  |  直到 14 年前
        1
  •  2
  •   Dave Bacher    16 年前
    eval ${Vegetable}=$(expr ${!Vegetable} - 1) 
    
        2
  •  2
  •   Dennis Williamson    16 年前

    尝试:

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

    你不需要使用 expr 顺便说一下。如您所见,bash可以处理整数算术。

    this page 有关bash中间接寻址的更多信息。

        3
  •  0
  •   ghostdog74    16 年前

    使用bash 4.0,您可以使用关联数组

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