How to execute multiple commands after double pipes in shell script

I am writing a Korn shell script where I have such a function

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

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

But I also want it to print 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 this will not work, the first return statement is always executed regardless of whether it some_command1succeeded 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 does not work, it seems that it returns only from subprocesses, not a function, and some_command2is executed regardless of whether it some_command1succeeded or failed.

echo "error while doing some_command2"; return 1, , .

+4
1

{ ...; ...; }, .

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

stderr :

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

, , :

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

- , POSIX.

+7

Source: https://habr.com/ru/post/1617832/


All Articles