help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] [newbie] fail on missing command/function?


From: Dan Douglas
Subject: Re: [Help-bash] [newbie] fail on missing command/function?
Date: Sat, 2 Jun 2012 00:05:27 +0000

On Fri, Jun 1, 2012 at 10:37 PM, Tom Roche <address@hidden> wrote:
>
> summary: How to make bash fail when one's script calls an undefined command

In the case of commands, common practice is to just call the command,
and if it fails, let it fail. This will of course work with all
control flow constructs that deal with exit status.

 $ blargbork; echo $?
-bash: blargbork: command not found
127

In the somewhat rarer event you need to test for the existence of a
command in advance, you can use type -p or possibly -P.

if cmd=$(type -p myCommand) && "$cmd"; then
    printf '%s found and executed successfully' "$cmd" >&2
fi

> or function?

The need to test whether a function is defined is exceedingly rare.
You're probably doing something wrong if you actually need this,
namely because functions can't be defined programmatically except via
eval (most definitely a last resort), and functions need to be
explicitly defined before they can be called. If you don't know if a
function is defined, you should change your program so you do. See:
http://mywiki.wooledge.org/BashFAQ/083

Essentially, you'll have to use either `declare -f', or `type -t'.

> I like to fail-fast

If you know what you're doing and promise not to ask questions,
there's `set -e' and the ERR trap. These are highly quirky and people
usually leave disappointed about their lack of usefulness - just a
heads up in advance if you run across them. Search bug-bash for the
MANY previous topics on set -e.

> producing traces...

Look at the "caller" builtin:
http://wiki.bash-hackers.org/commands/builtin/caller

--
Dan Douglas



reply via email to

[Prev in Thread] Current Thread [Next in Thread]