When do we need curly braces around shell variables?

后端 未结 7 1117
春和景丽
春和景丽 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:03

    Following SierraX and Peter's suggestion about text manipulation, curly brackets {} are used to pass a variable to a command, for instance:

    Let's say you have a sposi.txt file containing the first line of a well-known Italian novel:

    > sposi="somewhere/myfolder/sposi.txt"
    > cat $sposi
    

    Ouput: quel ramo del lago di como che volge a mezzogiorno

    Now create two variables:

    # Search the 2nd word found in the file that "sposi" variable points to
    > word=$(cat $sposi | cut -d " " -f 2)
    
    # This variable will replace the word
    > new_word="filone"
    

    Now substitute the word variable content with the one of new_word, inside sposi.txt file

    > sed -i "s/${word}/${new_word}/g" $sposi
    > cat $sposi
    

    Ouput: quel filone del lago di como che volge a mezzogiorno

    The word "ramo" has been replaced.

提交回复
热议问题