当 python 脚本失败时,我如何停止执行 bash 脚本?

时间:2021-01-20 02:40:15

标签: python bash error-handling sh

所以我的 shell 脚本中有以下内容:

python get_link.py $password | wget --content-disposition -i-
mkdir web_folder
mv *.zip web_folder

所以第一行是执行一个python脚本我写的打印出网站链接wget立即检索python脚本返回的链接并下载一个 zip 文件。

第二行创建一个名为“web_folder”的新文件夹第三行将 wget 下载的 zip 文件移动到“web_folder”中

我面临的问题是,如果 python 脚本由于 $password 密码错误等错误而失败,shell 脚本命令的其余部分仍在执行。就我而言,将打印以下内容:

mv: cannot stat ‘*.zip’: No such file or directory

即使 python 脚本失败,mkdir 和 mv 命令仍然会执行。当python脚本失败时,我如何确保脚本完全停止?

2 个答案:

答案 0 :(得分:3)

如果您使用 bash,请查看 PIPESTATUS 变量。 ${PIPESTATUS[0]} 将获得第一个管道的返回码。

#!/bin/bash
python get_link.py $password | wget --content-disposition -i-
if  [ ${PIPESTATUS[0]} -eq 0 ]
then
    echo "python get_link.py successful code here"
else
    echo "python get_link.py failed code here"
fi

答案 1 :(得分:0)

一个紧凑的解决方案,用 and 链接所有内容:

(python get_link.py $password | wget --content-disposition -i-) && (mkdir web_folder) && (mv *.zip web_folder)

不太紧凑的解决方案:

python get_link.py $password | wget --content-disposition -i-
if [ $? -eq 0 ]; then
  mkdir web_folder
  mv *.zip web_folder
fi