0

As closing "fi"s for nested if-blocks are not necessary except for when delimiting else-blocks (ref: https://stackoverflow.com/a/15328027/1942997), I was wondering if there were any implications when doing this or if it is just a matter of style.

Example Code 1:

if [ condition ]; then
    echo "Not nested, condition 1 true"
    if [ other_condition ]; then
        echo "Nested, condition 2 true"
    else
        echo "Nested, condition 2 false"
    fi
fi

Example Code 2 (notice the missing last fi):

if [ condition ]; then
    echo "Not nested, condition 1 true"
    if [ other_condition ]; then
        echo "Nested, condition 2 true"
    else
        echo "Nested, condition 2 false"
fi

Being used to closing every if block with curly brackets from other languages, it only seems reasonable to me to keep this behavior in bash scripting. The only impact I could think of was the marginally increased file size of the script in favor of better readability.

1

You tagged this as bash; I get "syntax error: unexpected end of file" if I don't close the inner if.

The referenced SO Q says:

In bash there isn't such a thing as every if has to be delimited by a companion fi marking the end of the if block.

which could be understood two ways:

The wrong way:

In bash there isn't such a thing as: "every if has to be delimited by a companion fi marking the end of the if block."

The right way:

In bash there isn't such a thing [as dangling else ambiguity], as every if has to be delimited by a companion fi marking the end of the if block.

  • 1
    Good answer. I added a ; to the original question, to make this more clear. Feel free to make more edits. – pfnuesel Feb 22 '16 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.