1

I am writing a bash function.

How do I make the control exit the function as soon as any command in it error out?

I have tried this:

function myFunc() {
    set +e
    cmd1
    cmd2
    set -e
}

It works but it closes my terminal as well.

Appreciate any ideas.

Thanks.

1
  • cmd1 || return; cmd2 || return? Commented Oct 3, 2015 at 18:11

3 Answers 3

4

"exit" means exit the shell. If you want to return from the function, you need to "return", which you can only do manually:

myFunc() {
  cmd1 || return $?
  cmd2 || return $?
}

If you really want to use set -e, use a subshell as well:

myFunc () {
  (
    set -e
    cmd1
    cmd2
  ) || return $?
}

Also consider using && to create a chain of commands each contingent on the success of the previous ones.

Sign up to request clarification or add additional context in comments.

Comments

2

Separate them by &&:

cmd1 && cmd2 && cmd3 

Comments

0

For truth tests without set -e one can test the value of #? to reveal the status of the last command:

#!/bin/bash


myfunc()
{
    true
    [ "$?" = "0" ] || return
    printf "passed truth test 1\n"

    true
    [ "$?" = "0" ] || return
    printf "passed truth test 2\n"

    false
    [ "$?" = "0" ] || return
    printf "passed false test\n"
}

myfunc

printf "passed continuation test\n"

Comments

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.