Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash:如果子函数失败,如何从父函数返回?_Bash_Shell_Sh - Fatal编程技术网

Bash:如果子函数失败,如何从父函数返回?

Bash:如果子函数失败,如何从父函数返回?,bash,shell,sh,Bash,Shell,Sh,我想清理一些代码,因此我想清理在每个命令之后进行的检查返回代码状态检查。如果命令失败,我将mid函数返回到父函数。 如果我将这段代码放在一个函数中,那么什么也不会发生,因为return命令将放在新的子函数中 当然,我想听听你的想法 当前状态: a(){ for i in $(cat file.txt) do scp $i hostb:/tmp/ if [ $? -ne 0 ] then print_fail

我想清理一些代码,因此我想清理在每个命令之后进行的检查返回代码状态检查。如果命令失败,我将mid函数返回到父函数。 如果我将这段代码放在一个函数中,那么什么也不会发生,因为return命令将放在新的子函数中

当然,我想听听你的想法

当前状态:

a(){
    for i in $(cat file.txt)
    do
        scp $i hostb:/tmp/

        if [ $? -ne 0 ]
        then
            print_failed "SCP failed."
            return 1
        fi
    done
}
期望的:

a(){
    for i in $(cat file.txt)
    do
        scp $i hostb:/tmp/

        # continue as usuall unless return code is not 0
        check_status $?
    done
}

check_status(){
    if [ $1 -ne 0 ]
    then
        print_failed "SCP failed."
        return 1
    fi
}

据我所知,如果子函数失败,则没有从父函数返回的隐式方法

我能想到的最接近的事情是这样的:

a () {
    while read -r source    # don't read lines with "for"!
    do
        check_status scp "$source" hostb:/tmp/ || return 1
    done < file.txt
}

check_status () {
    if ! "$@"
    then
        print_failed "SCP failed."
        return 1
    fi
}

它背后的想法是,所有这些都高于代码的可读性。。如果检查返回代码的父函数中仍然存在
If
,然后,它与原始代码没有太大区别。您可以使用
exit
而不是
return
,但这会扼杀整个脚本-这就是您想要的吗?不能使用
exit
。我编辑以在父函数中显示速记,但我认为原始问题的简单答案是“不,这不可能”.这也是答案:)
a () {
    while read -r source
    do
        if ! scp "$source" hostb:/tmp/
        then
            print_failed "SCP failed."
            return 1
        fi
    done < file.txt
}