如何在shell脚本中的双管道后执行多个命令

asi*_*swt 4 unix shell ksh

我正在写一个Korn shell脚本,我有这样的函数

#!/bin/ksh
myfunc() {
    some_command1 || return 1
    some_command2 || return 1
    ...
}
Run Code Online (Sandbox Code Playgroud)

换句话说,我将双管道后跟一个return语句,以便在命令失败时立即返回该函数.

但我也希望它在返回之前打印一些错误信息,我试过了

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

但它不起作用,无论some_command1成功还是失败,第一个返回语句总是被执行.

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

也不起作用,它似乎只从子进程返回而不是函数并且some_command2无论some_command1是成功还是失败都会被执行.

有没有办法对语句进行分组,echo "error while doing some_command2"; return 1以便它们只有在前面的命令失败时才能一起执行.

Hen*_*eld 9

直接的方法是使用{ ...; ...; },它结合命令而不创建子shell.

some_command1 ||
    { echo "error while doing some_command1"; return 1; }
Run Code Online (Sandbox Code Playgroud)

我建议使用stderr来获取错误消息:

some_command1 ||
    { echo "error while doing some_command1" >& 2; return 1; }
Run Code Online (Sandbox Code Playgroud)

只是因为我可以,我会告诉你我的秘密捷径:

some_command1 ||
    return 1 $(echo "error while doing some_command1" >& 2)
Run Code Online (Sandbox Code Playgroud)

最后一点是非常规的,但仍然是便携式POSIX外壳.

  • @asinkxcoswt,`{`和`}`**必须**周围有空格.请参阅https://www.gnu.org/software/bash/manual/bashref.html#Command-Grouping (4认同)