Bash convention for if ; then

后端 未结 5 781
野趣味
野趣味 2021-02-15 11:42

From this web page :

http://tldp.org/LDP/abs/html/abs-guide.html

It\'s mentioned the usage of the if bracket then convention which need a space after the semicol

相关标签:
5条回答
  • 2021-02-15 11:54

    I've never came across a shell that required a space in that context. Just to make sure, I've asked on c.u.s., you can read the replies here.

    0 讨论(0)
  • 2021-02-15 11:57

    Semicolon ; is an operator (not a keyword, like braces { }or a bang !) in Shell, so it doesn't need to be delimited with white space to be recognized in any POSIX-compliant shell.

    However, doing so improves readability (for my taste).

    Semicolon needs to be escaped if you mean a symbol "semicolon", not an operator.

    0 讨论(0)
  • 2021-02-15 12:02

    The space after the semicolon is not required by the syntax for any shell I know of, but it's good style and makes the code easier to read.

    I suppose the "sometimes needs to be escaped" wording refers to cases like echo foo\;bar, where you don't want the semicolon to be interpreted as a separator by the shell.

    0 讨论(0)
  • 2021-02-15 12:09

    I do not believe that the space should be necessary there. There's nothing about requiring spaces in the POSIX sh spec.

    Empirically, the following works fine in both bash 4.1.5(1) and dash:

    $ if true;then echo hi;else echo bye;fi
    hi
    $ 
    
    0 讨论(0)
  • 2021-02-15 12:14

    This has become the style in the last few years:

    if [ -x "$filename" ]; then
       echo "hi"
    fi
    

    However, back when dinosaurs like Burroughs and Sperry Rand ruled the earth, I learned to write if statements like this:

    if [ -x "$filename" ]
    then
        echo "hi"
    fi
    

    Then, you don't even need a semicolon.

    The new style with then on the same line as the if started in order to emulate the way C and other programming languages did their if statements:

    if (! strcmp("foo", "bar")) {
       printf "Strings equal\n";
    }
    

    These programming languages put the opening curly brace on the same line as the if.

    0 讨论(0)
提交回复
热议问题