diff --git a/README.md b/README.md index c1630f1..fa39cc7 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,20 @@ I’m coming across having to write the same shell script bits occasionally, and - Write once (here) and copypasta everywhere. - sh compatible if possible +# Examples + +This section shows example usages for common shell patterns. + +## Trap errors + +[trap_error_example.sh](trap_error_example.sh): If you run a script with -e that produces state that you want to clean up if anything goes wrong in your script. + +[trap_exit_example.sh](trap_exit_example.sh): if you run a script that launches other processes, and you want to make sure those processes exit when your script exists. # Functions +This section documents reusable functions for your scripts. + ## `wait_for_url $url $duration $iterations` Wait for a particular URL to be available using `curl`. Wait `$duration` seconds between attempts, try `$iterations` times. Defaults to `1` seconds and `3` times. diff --git a/trap_error_example.sh b/trap_error_example.sh new file mode 100644 index 0000000..dd10dcc --- /dev/null +++ b/trap_error_example.sh @@ -0,0 +1,9 @@ +# if you run a script with -e that produces state that you want to clean up if anything goes wrong in your script, this helps: + +trap 'handle_error' ERR + +handle_error () { + echo "an error has occured, let’s clean up some stuff" + # rm some-stuff.txt +} + diff --git a/trap_exit_example.sh b/trap_exit_example.sh new file mode 100644 index 0000000..c2c5922 --- /dev/null +++ b/trap_exit_example.sh @@ -0,0 +1,3 @@ +# if you run a script that launches other processes, and you want to make sure those processes exit when your script exists, this helps: + +trap 'kill $(jobs -p)' EXIT \ No newline at end of file