代码之家  ›  专栏  ›  技术社区  ›  Maxxx

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

  •  0
  • Maxxx  · 技术社区  · 4 年前

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

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

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

    第二条线 创建新文件夹 称为“web_folder”和 第三行是移动zip文件 wget将其下载到“web_folder”中

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

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

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

    0 回复  |  直到 4 年前
        1
  •  3
  •   John    4 年前

    如果您正在使用bash,请查看PIPESTATUS变量。 ${PIESTATUS[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
    
        2
  •  0
  •   brunoff    4 年前

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

    (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