Skip to content

Shell Script 3 Finger Claw⚓︎


What is the 3 Finger Claw⚓︎

The 3 Finger Claw for Unix and Linux shells is a quick and easy way to add error checking to shell scripts. They have been tested heavily by others to be as compatible as possible with all shells and POSIX.

There are many uses, but as an example they give cd /missing/path. Most systems will not have this path, but if the script assumes the directory exists from this command on the current directory is incorrect. Could this cause your script to perform actions in the wrong directory?

By wrapping the cd in the 3 finger claw your script is protected from doing actions you didn’t want as it will exit when you try cd /missing/path

Code⚓︎

Bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env sh

# POSIX compatible functions to enable reliable scripts

# credit to original authors
# 3 finger claw - https://youtu.be/S_aTzXVRRlM
# William Baxter (safe/try pattern originator)
# Matthew Story (loads of use)
# okan@ (try refinements, config conventions)
# Allan Jude (try - the actual name)

# place the following at the top of your script
shout() { echo "$0: $*" >&2; }
die() { shout "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }

# example usage with optional logger

logger "Starting 3 finger protected commands"
try cd /some/place
try tar xfv /missing/file.tar
logger "Finished 3 finger protected commands"

true

References⚓︎

Shell FU by Isaac (.ike) Levy - YouTube