How to use double or single brackets, parentheses, curly braces

后端 未结 7 956
心在旅途
心在旅途 2020-11-21 23:10

I am confused by the usage of brackets, parentheses, curly braces in Bash, as well as the difference between their double or single forms. Is there a clear explanation?

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 23:43

    1. A single bracket ([) usually actually calls a program named [; man test or man [ for more info. Example:

      $ VARIABLE=abcdef
      $ if [ $VARIABLE == abcdef ] ; then echo yes ; else echo no ; fi
      yes
      
    2. The double bracket ([[) does the same thing (basically) as a single bracket, but is a bash builtin.

      $ VARIABLE=abcdef
      $ if [[ $VARIABLE == 123456 ]] ; then echo yes ; else echo no ; fi
      no
      
    3. Parentheses (()) are used to create a subshell. For example:

      $ pwd
      /home/user 
      $ (cd /tmp; pwd)
      /tmp
      $ pwd
      /home/user
      

      As you can see, the subshell allowed you to perform operations without affecting the environment of the current shell.

    4. (a) Braces ({}) are used to unambiguously identify variables. Example:

      $ VARIABLE=abcdef
      $ echo Variable: $VARIABLE
      Variable: abcdef
      $ echo Variable: $VARIABLE123456
      Variable:
      $ echo Variable: ${VARIABLE}123456
      Variable: abcdef123456
      

      (b) Braces are also used to execute a sequence of commands in the current shell context, e.g.

      $ { date; top -b -n1 | head ; } >logfile 
      # 'date' and 'top' output are concatenated, 
      # could be useful sometimes to hunt for a top loader )
      
      $ { date; make 2>&1; date; } | tee logfile
      # now we can calculate the duration of a build from the logfile
      

    There is a subtle syntactic difference with ( ), though (see bash reference) ; essentially, a semicolon ; after the last command within braces is a must, and the braces {, } must be surrounded by spaces.

提交回复
热议问题