yl35
yl35

Reputation: 111

Bash: what's the advantage of using exit ${1:0} instead of exit $1

I found the following code snippet in Archlinux's mkinitcpio script.

cleanup() {
    if [[ $workdir ]]; then
        # when PRESET is set, we're in the main loop, not a worker process
        if (( SAVELIST )) && [[ -z $PRESET ]]; then
            msg "build directory saved in %s" "$workdir"                                                                                                                        
        else
            rm -rf "$workdir"
        fi
    fi

    exit ${1:0}
}

Is the exit ${1:0} here redundant? Why not just simply write exit $1. I tested this function with arguments such as 1, -1, 130, no difference between the simple and complex version.

Upvotes: 2

Views: 1117

Answers (3)

rodion
rodion

Reputation: 15029

To add to other answers: it's redundant in this case, because exit without any arguments would be have the same way as exit 0. Therefore exit $1 and exit ${1:-0} are effectively the same.

Upvotes: 0

FatalError
FatalError

Reputation: 54571

As it stands, it seems redundant as taking the substring of the variable from index 0 is... well the same value. However, an empty string to exit is the same as exit 0. Now, if it were exit ${1:-0} it would make perfect sense -- then 0 (success) would be the default exit value, and would be used in the absence of paramter $1. However, explicitly passing 0 isn't necessary.

Upvotes: 2

Random832
Random832

Reputation: 39020

This allows it to be used with no argument (or an empty string argument) and result in exit 0. This is different from using exit by itself, because exit alone uses the exit status from the previous command. Even if msg or rm aren't expected to result in a status other than 0, this saves the author from having to think about this when changing the code.

Upvotes: 2

Related Questions