GoTTimw
GoTTimw

Reputation: 2430

detecting command not found in bash script

I have a series of command to execute. However I need to exit whenever 'command is not found' error occurs. So post execution check of output is not an option

The "$?" variable is equal zero when 'command is not found' and on success.

Upvotes: 7

Views: 12607

Answers (4)

Eric
Eric

Reputation: 343

Take jq as an example:

jq --version || echo "Please install [jq](https://stedolan.github.io/jq/download) first." &&  exit 1

Upvotes: 0

user1019830
user1019830

Reputation:

If this should be done from a script, it's natural to use a conditional to express this kind of behaviour:

asdf 2> /dev/null || exit 1

Upvotes: 8

TrueY
TrueY

Reputation: 7610

UPDATED

Try

[ -x "$executable" ] && echo "Command '$executable' not found" >&2 && exit 1

This will write an error to stderr and exit with 1 exit code.

If You have just the name of the utility You can check its path with type build-in.

Example:

type type
type ls
type xls

Output:

type is a shell builtin
ls is /usr/bin/ls
./test.sh: line 13: type: xls: not found

Test returns 1 if utility not found.

So if the $executable can be anything (a build-in, alias, binary, ...), then this could be used:

type -p ls>/dev/null && ls -l
type -p xls>/dev/null && xls --some_arg

This will run ls (any executable), but not xls.

Anyway if in the script the execfail option is not set (shopt) then the script will exit after stating the bash: some_utility: command not found error message. If this option is set, then it continues. But You can trap the pseudo signal ERR and do what You need:

shopt -s execfail
fnc() { echo $?, $_, Oops;}
trap fnc ERR

ls -d *|head -2
xls
yls

Output:

a1
a2
./test_tLcn.sh: line 8: xls: command not found
127, xls, Oops
./test_tLcn.sh: line 9: yls: command not found
127, yls, Oops

Upvotes: 2

chepner
chepner

Reputation: 531035

If the command is not found, the exit status should be 127. However, you may be using bash 4 or later and have a function called command_not_found_handle defined. This function is called if a command cannot be found, and it may exit 0, masking the 127 code.

Running type command_not_found_handle will show the definition of the function if it is defined. You can disable it by running unset command_not_found_handle.

Upvotes: 6

Related Questions