How to Execute Multiple Command After Double Pipes in Shell Script

I am writing a Korn shell script where I have a function like this

#!/bin/ksh
myfunc() {
    some_command1 || return 1
    some_command2 || return 1
    ...
}

In words, I put the double pipes followed by a return statement so that the function return immediately when a command fails.

But I also want that it prints some error messages before returning, I tried

#!/bin/ksh
myfunc() {
    some_command1 || echo "error while doing some_command1"; return 1
    some_command2 || echo "error while doing some_command2"; return 1
    ...
}

But it does not work, the first return statement always get executed no matter some_command1 has succeeded or failed.

And

#!/bin/ksh
myfunc() {
    some_command1 || (echo "error while doing some_command1"; return 1)
    some_command2 || (echo "error while doing some_command2"; return 1)
    ...
}

also doesn't work, it seems it only return from sub processes not the function and some_command2 get executed no matter some_command1 has succeeded or failed.

Is there a way to group the statements echo "error while doing some_command2"; return 1 such that they both get executed together only when the preceding command fails.

2

1 Answer

The straightforward way is to use { ...; ...; }, this combines the commands without creating a subshell.

some_command1 ||
    { echo "error while doing some_command1"; return 1; }

I do recommend to use stderr for error messages, though:

some_command1 ||
    { echo "error while doing some_command1" >& 2; return 1; }

And just because I can, I'll give you my secret shortcut:

some_command1 ||
    return 1 $(echo "error while doing some_command1" >& 2)

That last bit is unconventional, but still portable POSIX shell.

4

Your Answer

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

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest