Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

前端 未结 9 2059
情话喂你
情话喂你 2020-11-22 03:58

A co-worker claimed recently in a code review that the [[ ]] construct is to be preferred over [ ] in constructs like

if [ \"`id -         


        
9条回答
  •  礼貌的吻别
    2020-11-22 04:53

    If you are into following Google's style guide:

    Test, [ and [[

    [[ ... ]] reduces errors as no path name expansion or word splitting takes place between [[ and ]], and [[ ... ]] allows for regular expression matching where [ ... ] does not.

    # This ensures the string on the left is made up of characters in the
    # alnum character class followed by the string name.
    # Note that the RHS should not be quoted here.
    # For the gory details, see
    # E14 at https://tiswww.case.edu/php/chet/bash/FAQ
    if [[ "filename" =~ ^[[:alnum:]]+name ]]; then
      echo "Match"
    fi
    
    # This matches the exact pattern "f*" (Does not match in this case)
    if [[ "filename" == "f*" ]]; then
      echo "Match"
    fi
    
    # This gives a "too many arguments" error as f* is expanded to the
    # contents of the current directory
    if [ "filename" == f* ]; then
      echo "Match"
    fi
    

提交回复
热议问题