Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute multiple command after double pipes in shell script

Tags:

shell

unix

ksh

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.

like image 894
asinkxcoswt Avatar asked Dec 24 '22 12:12

asinkxcoswt


1 Answers

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.

like image 139
Henk Langeveld Avatar answered Dec 27 '22 08:12

Henk Langeveld