When do we need curly braces around shell variables?

后端 未结 7 1103
春和景丽
春和景丽 2020-11-22 01:39

In shell scripts, when do we use {} when expanding variables?

For example, I have seen the following:

var=10        # Declare variable

         


        
7条回答
  •  旧巷少年郎
    2020-11-22 02:10

    Variables are declared and assigned without $ and without {}. You have to use

    var=10
    

    to assign. In order to read from the variable (in other words, 'expand' the variable), you must use $.

    $var      # use the variable
    ${var}    # same as above
    ${var}bar # expand var, and append "bar" too
    $varbar   # same as ${varbar}, i.e expand a variable called varbar, if it exists.
    

    This has confused me sometimes - in other languages we refer to the variable in the same way, regardless of whether it's on the left or right of an assignment. But shell-scripting is different, $var=10 doesn't do what you might think it does!

提交回复
热议问题