From 88fc5bc98370066490a9670c6b28fba91efd7d4d Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Tue, 20 Aug 2024 01:03:48 +0200 Subject: zsh,bash: trap handling --- src/shells/bash.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'src/shells/bash.md') diff --git a/src/shells/bash.md b/src/shells/bash.md index f27b3a2..fb511b8 100644 --- a/src/shells/bash.md +++ b/src/shells/bash.md @@ -133,6 +133,40 @@ v=abc ; ( v=foo; echo $v; ) ; echo $v # abc ``` +## Trap Handling + +```bash +trap "" /EXIT + +# Show current trap handler. +trap -p +# List signal names. +trap -l +``` + +#### Example: Run handler only on error exit +```bash +trap 'test $? -ne 0 && echo "run exit trap"' EXIT + +# -> no print +exit 0 +# -> print +exit 1 +``` + +#### Example: Mutex in shell script +For example if a script is triggered in unsynchronized, we may want to ensure +that a single script instance runs. +```bash +# open file=LOCK with fd=100 +exec 100>LOCK +# take exclusive lock, wait maximal for 3600s +flock -w 3600 -x 100 || { echo "flock timeout"; exit 1; } + +# eg automatically release lock when script exits +trap "flock -u 100" EXIT +``` + ## Argument parsing with `getopts` The `getopts` builtin uses following global variables: -- cgit v1.2.3