Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portably trapping ERR in shell script

I'm trying to write a shell script that aborts when a command fails and displays the offending line number.

set -e
trap 'echo "$0 FAILED at line ${LINENO}"' ERR

Turned out the trap line does not work with Ubuntu's default shell script interpreter, dash. If I change the shebang line to #!/bin/bash this works but not with #!/bin/sh. Is there a way to make this work without relying on bash being present?

By the way, The error I get from dash is this:

trap: ERR: bad trap
like image 947
Elektito Avatar asked Jul 09 '15 09:07

Elektito


2 Answers

You can trap on exit and test the exit code like this:

set -e
trap '[ $? -eq 0 ] && exit 0 || echo "$0 FAILED at line ${LINENO}"' EXIT
like image 87
ewatt Avatar answered Sep 19 '22 12:09

ewatt


According to various sources on the internets, ERR is not standard at all and only supported by the Korn Shell - which seemed to invent it - and Bash, which seemed to adopt it. https://github.com/bmizerany/roundup/issues/25#issuecomment-10978764

I would go for the easy solution.

Simply change

#!/bin/sh

to

#!/bin/bash

or better

#!/usr/bin/env bash
like image 27
organic-mashup Avatar answered Sep 18 '22 12:09

organic-mashup