why don’t statements behave the same in this case?

Why this happens?

Facts:

  • The exit status of a function is equal to the exit status of the last command executed (or equal to what is passed to return).
  • The exit status of a list of commands is equal to the exit status of the last command executed.
  • The exit status of an if statement is the last command executed, except if no body was executed, when the exit status is 0.
  • The exit status of 0 represents success, a non-zero exit status represents failure.

Consider the following function:

func() {
    false && return 1
}

First false returns nonzero exit status. Because it’s nonzero, the return 1 is not executed. Then the exit status of the whole list of commands is the exit status of last command executed. The exit status of the whole ( false && return 1 ) is equal to the exit status of false. Then, the exit status of the whole function is equal to the exit status of the last command executed. Ie. the exit status of func is equal to the exit status of false.

Doing some_command && return 1 is just strange if it’s the last command in a function – just do ! some_command. Maybe you’ll want to do:

func() {
    local linecont
    linecont=$(sed '$1!d' "$dbfile")
    [ -n "$linecont" ]
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top