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.
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.
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 ls /this/file/does/not/exist 2>/dev/null ? ls command still exists.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.
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 bash 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 $executable is a path to the executable you are looking for. -x does not perform path lookups.type.ERR seems overly broad, since that function will run on any error, not just a command-not-found error.$? is 127 then it can be detected that the command-not-found error occurred. $_ can be used to print the not found utility.