bash assign default value

前端 未结 4 1694
一生所求
一生所求 2020-12-22 16:55

${parameter:=word} Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of pa

4条回答
  •  [愿得一人]
    2020-12-22 17:41

    Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples

    ${parameter-default}, ${parameter:-default}
    

    If parameter not set, use default. After the call, parameter is still not set.
    Both forms are almost equivalent. The extra : makes a difference only when parameter has been declared, but is null.

    unset EGGS
    echo 1 ${EGGS-spam}   # 1 spam
    echo 2 ${EGGS:-spam}  # 2 spam
    
    EGGS=
    echo 3 ${EGGS-spam}   # 3
    echo 4 ${EGGS:-spam}  # 4 spam
    
    EGGS=cheese
    echo 5 ${EGGS-spam}   # 5 cheese
    echo 6 ${EGGS:-spam}  # 6 cheese
    

    ${parameter=default}, ${parameter:=default}
    

    If parameter not set, set parameter value to default.
    Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

    # sets variable without needing to reassign
    # colons suppress attempting to run the string
    unset EGGS
    : ${EGGS=spam}
    echo 1 $EGGS     # 1 spam
    unset EGGS
    : ${EGGS:=spam}
    echo 2 $EGGS     # 2 spam
    
    EGGS=
    : ${EGGS=spam}
    echo 3 $EGGS     # 3        (set, but blank -> leaves alone)
    EGGS=
    : ${EGGS:=spam}
    echo 4 $EGGS     # 4 spam
    
    EGGS=cheese
    : ${EGGS:=spam}
    echo 5 $EGGS     # 5 cheese
    EGGS=cheese
    : ${EGGS=spam}
    echo 6 $EGGS     # 6 cheese
    

    ${parameter+alt_value}, ${parameter:+alt_value}
    

    If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
    Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

    unset EGGS
    echo 1 ${EGGS+spam}  # 1
    echo 2 ${EGGS:+spam} # 2
    
    EGGS=
    echo 3 ${EGGS+spam}  # 3 spam
    echo 4 ${EGGS:+spam} # 4
    
    EGGS=cheese
    echo 5 ${EGGS+spam}  # 5 spam
    echo 6 ${EGGS:+spam} # 6 spam
    

提交回复
热议问题