如何在不调用命令替换的情况下调用Bash函数?

时间:2014-11-26 15:38:43

标签: bash command-substitution

我有一个Bash函数,它有一个Perl风格的"或者死"。例如,

#!/bin/bash
func1 () {
    local val
    val=`cat foobar` || exit 7
    echo "func1: cat returns $?"
}

myval=`func1`
echo "Line X should not be reached (retn = $? val = $myval)"
myval=$(func1)
echo "Line Y should not be reached (retn = $? val = $myval)"
func1
echo "Line Z should not be reached (retn = $?)"

直接调用函数让我利用exit。但是,如果函数返回我想要使用的值,则命令替换不适用于exit。也就是说,退出只存储在返回值$?中,并执行下一行。

使用调试选项-x运行似乎意味着命令替换类似于子shell,因为bash为它输出更深的嵌套。因此,exit不适用于主脚本。

示例输出:

cat: foobar: No such file or directory
Line X should not be reached (retn = 7 val = )
cat: foobar: No such file or directory
Line Y should not be reached (retn = 7 val = )
cat: foobar: No such file or directory

有没有办法调用func1并使用其输出(在变量,循环,if等中),同时仍然利用短路exit

1 个答案:

答案 0 :(得分:0)

您可以使用包含SIGHUP信号处理程序的这个简单代码,它可以完美地工作:)

hndlHUP () {
    exit 7
}
func1 () {
    local val
    val=$(cat foobar) || kill -SIGHUP $$
    echo "func1: cat returns $?"
}

trap hndlHUP SIGHUP

myval=`func1`
echo "Line X should not be reached (retn = $? val = $myval)"
myval=$(func1)
echo "Line Y should not be reached (retn = $? val = $myval)"
func1
echo "Line Z should not be reached (retn = $?)"