Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

I wonder if there is a simpler 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 am looking for is something like

exec_if_exist $name

which eliminates repetition of the script name.

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

Best

like image 699
Jaro Avatar asked Feb 21 '14 06:02

Jaro


People also ask

How do I make sure only one instance of a Bash script runs?

Just add the pidof line at the top of your Bash script, and you'll be sure that only one instance of your script can be running at a time.

How do I run a Bash script without executing?

There can be situations where we may want to validate the script syntactically prior to its execution. If so, we can invoke the noexec mode using the -n option. As a result, Bash will read the commands but not execute them.

What does != Mean in Bash?

The origin of != is the C family of programming languages, in which the exclamation point generally means "not". In bash, a ! at the start of a command will invert the exit status of the command, turning nonzero values to zero and zeroes to one.

How do you check if a file already exists in Bash?

-e: It returns True if any type of file exists. -c: It returns True if the character file exists. -r: It returns True if a readable file exists. –w: It returns True if a writable file exists.


2 Answers

type did not seem to always work on OS X. What worked was

which -s command && command
like image 180
serv-inc Avatar answered Sep 20 '22 15:09

serv-inc


Why not

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

And, the path may need to be considered when invoking $1.

like image 42
nicky_zs Avatar answered Sep 18 '22 15:09

nicky_zs