Mikhail T.
Mikhail T.

Reputation: 3997

exec for a sh function

A commonly-used program here is often invoked at the ends of the shell scripts and we use exec to skip the implicit fork and prevent sh-process from waiting for the command to finish:

...
exec mycommand
# Unreached

Lately, however, we implemented a wrapper function around the command in order to have some common arguments inside it:

...
function mycommand () {
    command mycommand -foo -bar "$@"
}

The code calling exec mycommand continues to call the actual program instead of calling into the function, so we had to replace it with just mycommand.

But now the calling shell waits for mycommand to finish...

Changing the function to always exec mycommand is not acceptable, because it is not always the last command in the script. Often, but not always.

How'd we get both: a wrapping function and the ability to exec the program without forking, when appropriate? Creating a separate function (exec_mycommand) seems ugly...

Upvotes: 0

Views: 495

Answers (1)

Ken Jackson
Ken Jackson

Reputation: 499

You could put exec after the function instead on in front of it.

function mycommand () {
    if [ "$1" = exec ]; then
        shift
        exec command mycommand -foo -bar "$@"
    else
        command mycommand -foo -bar "$@"
    fi
}

Then in the main body put either mycommand exec or mycommand.

Upvotes: 1

Related Questions