我有这样的功能
function generic_build_a_module(){
move_to_the_right_directory
echo 'copying the common packages'; ./build/build_sdist.sh;
echo 'installing the api common package'; ./build/cache_deps.sh;
}
如果./build/build_sdist.sh
未成功完成,我想退出该功能。
这是内容./build/build_sdist.sh
... multiple operations....
echo "installing all pip dependencies from $REQUIREMENTS_FILE_PATH and placing their tar.gz into $PACKAGES_DIR"
pip install --no-use-wheel -d $PACKAGES_DIR -f $PACKAGES_DIR -r $REQUIREMENTS_FILE_PATH $PACKAGES_DIR/*
换句话说,主要功能generic_build_a_module
如何“知道” ./build/build_sdist.sh
是否成功完成?
答案 0 :(得分:1)
您可以通过用if
包围命令来检查命令的退出状态。 !
反转退出状态。使用return 1
以退出状态1退出函数。
generic_build_a_module() {
move_to_the_right_directory
echo 'copying the common packages'
if ! ./build/build_sdist.sh; then
echo "Aborted due to error while executing build."
return 1
fi
echo 'installing the api common package'
./build/cache_deps.sh;
}
如果您不想打印错误消息,可以使用||
来缩短同一程序的编写时间。
generic_build_a_module() {
move_to_the_right_directory
echo 'copying the common packages'
./build/build_sdist.sh || return 1
echo 'installing the api common package'
./build/cache_deps.sh;
}
或者,您可以使用set -e
。当某些命令以非零状态退出时,这将立即退出脚本。
答案 1 :(得分:0)
您必须执行以下操作:-
在后台运行两个脚本并将其各自的进程ID存储在两个变量中
每隔1到2秒间隔检查脚本是否完成。
杀死在特定时间(例如30秒)后未完成的过程
示例:
sdist=$(ps -fu $USER|grep -v "grep"|grep "build_sdist.sh"| awk '{print $2}')
OR
sdist=$(ps -fu $USER|grep [b]uild_sdist.sh| awk '{print $2}')
deps=$(ps -fu $USER|grep -v "grep"|grep "cache_deps.sh"| awk '{print $2}')
现在使用while
循环在一定时间间隔后每次检查状态,或者像下面这样仅在30秒后直接检查状态
sleep 30
if grep "$sdist"; then
kill -8 $sdist
fi
if grep "$deps"; then
kill -8 $deps
fi
答案 2 :(得分:0)
您可以通过检查$?
变量来检查最后执行的命令的退出代码状态。退出代码0是命令成功完成的典型指示。
退出代码可以通过使用exit
以及脚本中的代码号来设置。
这里有a previous question关于如何使用$?
的更多信息,但是要简单地检查此值,请尝试:
echo "test";echo $?
# Example
echo 'copying the common packages'; ./build/build_sdist.sh;
if [ $? -ne 0 ]; then
echo "The last command exited with a non-zero code"
fi
[ $? -ne 0 ]
检查是否最后执行的命令错误代码不等于0。这对于确保捕获任何生成的负错误代码(例如-1)也很有用。
上述方法的警告是,我们仅检查了最后执行的命令,而不是您提到的... multiple operations....
,因此我们可能错过了由命令生成的错误在pip install
之前执行。
根据情况,您可以在后续脚本中set -e
进行操作,该脚本指示外壳程序在第一次出现时以非零状态退出命令。
另一种选择是执行与./build/build_sdist.sh
中的示例类似的操作,以检查每个命令的退出代码。这样一来,您就可以最大程度地控制脚本的时间和完成方式,并允许脚本设置自己的exit
代码。