How to execute a script only if it is present in bash?

I wonder if there is an easier way to execute a script in bash only if this script exists. What I want is equivalent to:

if [ -x $name ]
then
  $name
fi

or

[ -x $name ] && $name

What I'm looking for is something like

exec_if_exist $name

which eliminates the repetition of the script name.

Is there a way to simplify this in bash? I do not need a function or "speculative" execution that would give the command an error not found.

The best

+6
source share
3 answers

You can simplify it with the command type. Your tests require a full or relative file path. With typeit, it will search for PATH.

type $name && $name

This is also good because it puts success on STDOUT and failure on STDERR, giving you full control over the output.

# mute success
type >/dev/null
# mute fail
type 2>/dev/null
# mute both
type &>/dev/null
+6

exec_if_exist() {
    test -x $1 && $1
}

, , $1.

+2

type OS X. , ,

which -s command && command
0

All Articles