2

I'm trying to learn how to use trap in bash. I'm on ubuntu ohmyzsh.

This is a test case, but I would wish to call a function with the params that was passed in when the function was called to the function that is called on exit. Right now it does not even call the function in trap.

xtest() {
    trap 'xecho' EXIT
    echo 'start'
    while :; do echo 'Hit CTRL+C'; sleep 1; done
}

xecho() {
    echo "done $1"
}

I just get

$ xtest foo
start
Hit CTRL+C
Hit CTRL+C
^C% 

I've noticed this answer to use SIGINT and to use exit in the function that gets called by trap, but then it closes the terminal, otherwise it doesn't stop the loop. So still confused and it doesn't help me with my example of getting the param foo echoed out on break.

Tjorriemorrie
  • 16,818
  • 20
  • 89
  • 131
  • http://zsh.sourceforge.net/Doc/Release/Shell-Builtin-Commands.html#index-trap – hek2mgl Nov 26 '19 at 23:47
  • Does this answer your question? [Is trap EXIT required to execute in case of SIGINT or SIGTERM received?](https://stackoverflow.com/questions/27012762/is-trap-exit-required-to-execute-in-case-of-sigint-or-sigterm-received) – hek2mgl Nov 26 '19 at 23:49
  • 1
    @Tjorriemorrie : You are asking for a `bash` solution, but are tagging your question `zsh` and also refer to zsh in your text, so, first of all, plesae be clear about what environment you are using. – user1934428 Nov 28 '19 at 08:50

2 Answers2

1

First, zsh is a different shell than bash. While many things are similar, a couple of other things are different.

Like mentioned in Is trap EXIT required to execute in case of SIGINT or SIGTERM received? the EXIT trap won't run in zsh when SIGINT is received, unlike bash. You need to use SIGINT instead.

Also note that xecho must explicitly call exit:

#!/usr/bin/zsh

xtest() {
    trap "xecho ${1}" INT
    echo 'start'
    while :; do echo 'Hit CTRL+C'; sleep 1; done
}

xecho() {
    echo "done $1"
    exit 0
}

xtest

In zsh the EXIT trap will be called upon regular exit of the script when defined in the main script and / or upon the exit of a function when defined in a function:

#!/usr/bin/zsh

trap "xecho ${0} ${1}" EXIT

xtest() {
    trap "xecho ${0} ${1}" EXIT
    echo "do something"
}

xecho() {
    echo "${1} ${2} done"
}

xtest foo
xtest bar

echo "main script ending"

Output:

do something
xtest foo done
do something
xtest bar done
main script ending
script.zsh  done
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

Very simple, just call the function as if you are normally invoking it

my_script.sh:

#!/usr/bin/env bash

function foo {
  echo "hi, foo is called"
  exit 123
}
trap 'foo' EXIT

sleep 30

bash cli:

$/home/my_script.sh # Process is sleeping
# Hitting CTRL+C
hi, foo is called
Mercury
  • 7,430
  • 3
  • 42
  • 54