# checking commands in script



## fluca1978 (Nov 2, 2012)

IN a lot of shell scripts I write I usually test for the presence of other external commands, that have all to be found and tested like the following:


```
PERL_CMD=$( which perl )
if [ -z "$PERL_CMD" ]
then
    # something wrong
fi
```

I was guessing if, apart from making the above a function, there is some smarter piece of code to search for and test the executable bit of a command by its name.


----------



## kpa (Nov 2, 2012)

You could write a function that splits the PATH by colons and test each directory for existence and executability of the binary and use the first match. It would be slightly faster than spawning a subshell.


----------



## jilles@ (Nov 3, 2012)

The below works without any external processes:

```
if ! command -v perl >/dev/null 2>&1; then
    # something wrong
fi
```

Note that a builtin, function or alias is also considered valid here.


----------



## fluca1978 (Nov 5, 2012)

While the usage of command(1) is good because it does not open another subshell, I was not looking for a fastest way but a smarter one, that is even using command(1) I have to place the full path in a variable and test if it is not-null (or test the command exit status). So my script will be full of if statements. I think writing a function to clean up the code is therefore the only way to go.


----------

