# Strange behaviour with "set -e" and functions

**URL:** <https://community.unix.com/t/strange-behaviour-with-set-e-and-functions/244939>\
**Category:** Shell Programming and Scripting\
**Created:** [July 19, 2009, 12:00pm UTC](https://community.unix.com/t/strange-behaviour-with-set-e-and-functions/244939 "2009-07-19T12:00:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tokland](https://community.unix.com/user_avatar/community.unix.com/tokland/32/4370_2.png) [@tokland](https://community.unix.com/u/tokland)\
**Post date:** [July 19, 2009, 12:00pm UTC](https://community.unix.com/t/strange-behaviour-with-set-e-and-functions/244939/1 "2009-07-19T12:00:44Z")

</div>

Hi,

This seems to be a recurrent problem on mailing lists and bug reports, but I've been unable to find a solution. Let's imagine we have this bash script:

```nohighlight
#!/bin/bash
set -e

fun() {
  echo "fun_start"
  test 1 = 2 
  echo "fun_end"
}

echo "main_start"
fun 
echo "main_end"

```

This outputs:

```nohighlight
main_start
fun_start

```

Right, but now I want the script to continue if "fun" fails, so I protect it with a "||":

```nohighlight
echo "main_start"
fun || echo "fun failed"
echo "main_end"

```

And that's what I get (!):

```nohighlight
main_start
fun_start
fun_end
main_end

```

The function continues even though there has been an error and my conditional statement is not even run. It seems that "set -e" is being ignored inside the function. That seems very counterintuitive. The only solution I found was adding "|| return 1" to every "dangerous" call inside a function, but then what's the point of using set -e?

So, am I doing something wrong? is there any easy way to get this desired output?

```nohighlight
main_start
fun_start
fun failed
main_end

```

thanks

---

<div class="post-metadata">

**Author:** ![kshji](https://community.unix.com/user_avatar/community.unix.com/kshji/32/15661_2.png) [@kshji](https://community.unix.com/u/kshji)\
**Post date:** [July 19, 2009, 12:42pm UTC](https://community.unix.com/t/strange-behaviour-with-set-e-and-functions/244939/2 "2009-07-19T12:42:55Z")

</div>

[Bash doc, set](http://www.gnu.org/software/bash/manual/bashref.html#Modifying-Shell-Behavior)

This is generic for every posix-shells:

```plaintext
fun() {
  echo "fun_start"
  test 1 = 2 || return 1
  echo "fun_end"
}

echo "main_start"
fun || echo "fun failed"
echo "main_end"

```
