1

I want to clean up some of my code, for that I want to clean the check return code status check I make after each command. If the command fails I return mid function to the parent function. If I'll take this code inside a function then nothing happens as the return command will be inside the new-child function.

Sure gald for some thoughts.

Current status:

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

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

Desired:

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
}

1 Answer 1

2

As far as I'm aware, there is no implicit way to return from the parent function if the child function failed.

The closest thing I can think of would be something like this:

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
}

The role of check_status is to execute a command and print the failure message if it didn't succeed. It also returns 1, so the parent function can use if ! or || to return as well.

There's no way of returning from the parent function except by using global variables, which I would personally avoid if possible.

To be honest though, I don't see the advantage of what you have over this:

a () {
    while read -r source
    do
        if ! scp "$source" hostb:/tmp/
        then
            print_failed "SCP failed."
            return 1
        fi
    done < file.txt
}
Sign up to request clarification or add additional context in comments.

5 Comments

The idea behinds it, it's all above code readness.. If there is still if in the parent function that check the return code, then it is not much different from the original code..
You could use exit instead of return but that would kill the whole script - is that what you want?
Can't use exit.
I edited to show a shorthand in the parent function but I think the simple answer to your original question is "no, it's not possible".
That's also an answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.