我正在尝试在 bash 脚本中编写一个函数,该脚本接受一个命令作为参数,执行该命令 -- 并且 -- 如果退出非零命令,则中止脚本:
文件: 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"
Run Code Online (Sandbox Code Playgroud)
称它为:
% ./command_wrapper.sh
./command_wrapper.sh:exec_cmd "grep -R somethingyouwillneverfind ."
rest of script running
Run Code Online (Sandbox Code Playgroud)
在使用非零退出的命令运行函数后,脚本继续执行 - 为什么?失败
时如何使此命令错误退出$command
?
您的功能按设计工作,但问题是您的假设不正确。grep -R somsomeoemoem .
不会错误退出。
尝试使用此命令查看退出的函数:
exec_cmd "false"
Run Code Online (Sandbox Code Playgroud)