Skip to content

Instantly share code, notes, and snippets.

@tonyskapunk
Last active January 23, 2019 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyskapunk/56276e2d8717a1c805e969e7325f8d95 to your computer and use it in GitHub Desktop.
Save tonyskapunk/56276e2d8717a1c805e969e7325f8d95 to your computer and use it in GitHub Desktop.
test trap on bash5

Create env with docker:

docker run --rm --name buster --tty --detach debian:buster
docker exec buster bash -c 'apt-get update && apt-get install bash -y'
docker exec -ti buster /bin/bash

Create a script with the trap function in it

cat > t.sh <<EOF
LF="/var/lock/t"

# Cleanup function to remove lock
cleanup() {
  echo "INFO [\$\$]: Caught signal - deleting \${LF}"
  rm -f "\${LF}"
  echo "Execution time: \${SECONDS}s"
}

lock() {
  (set -C; echo "\$\$" > "\${LF}") 2>/dev/null
  if [[ \$? -ne 0 ]]; then
    echo "ERROR [\$\$]: Lock File exists - exiting"
    exit 1
  else
    trap 'exit 2' 1 2 15 17 23
    trap 'cleanup' EXIT
    echo "INFO[\$\$]: Created lock file: \${LF}"
  fi
}

lock
echo -n sleeping some...
for i in {0..9}; do
  sleep 1
done
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment