I am trying to write a function in a bash script which accepts a command as an argument, executes the command -- AND -- if the command non-zero exited, abort the script:
file: command_wrapper.sh
#!/usr/bin/env bash
function exec_cmd() {
local command=${1}
$command || exit # run the command if $? is 1 exit
if [[ $? -eq 1 ]] # AGAIN if $? is 1 exit
then
echo "command failed"
exit
fi
return 0
}
exec_cmd "grep -R somsomeoemoem ." # call the function, passing a
# command that will exit with 1
echo "rest of script running"
call it:
% ./command_wrapper.sh
./command_wrapper.sh:exec_cmd "grep -R somethingyouwillneverfind ."
rest of script running
the script carries on after the function is run with a command that non-zero exits - why?
How can I get this command to error exit when $command
fails?