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

如果两台计算机中的文件都丢失,如何以非零状态退出shell脚本?

  •  0
  • AKIWEB  · 技术社区  · 11 年前

    我正在运行以下shell脚本 machineA 正在复制文件的 machineB machineC 进入 机器A 。如果文件不在 机器B ,那么它应该在里面 机器C 。文件不会在 机器B 机器C ,他们将有唯一的文件,所以假设我有总数 100 files ,所以可能 40 files 位于 机器B 和剩余 60 files 将在 机器C .

    我需要复制一些文件 PRIMARY 中的目录 机器A 和一些文件 SECONDARY 中的目录 机器A .

    下面是我的shell脚本,它运行良好,但我想处理一些角落的情况,例如-

    • 在某些情况下,假设文件在 机器B 机器C ,然后我想退出具有非零状态(未成功)的shell脚本,并返回错误,其中包含在中不可用的文件号 机器B 机器C 二者都

    下面是我的shell脚本-

    #!/bin/bash
    
    readonly PRIMARY=/test01/primary
    readonly SECONDARY=/test02/secondary
    readonly FILERS_LOCATION=(machineB machineC)
    readonly LOCATION=/bat/test/pe_t1_snapshot
    
    PRIMARY_PARTITION=(1003 1012 1031) # this will have more file numbers
    SECONDARY_PARTITION=(1005 1032 1067)  # this will have more file numbers
    
    dir1=/bat/test/pe_t1_snapshot/20140320
    dir2=/bat/test/pe_t1_snapshot/20140320
    
    if [ "$dir1" = "$dir2" ]
    then
    
        # delete first and then copy the files in primary directory
        find "$PRIMARY" -mindepth 1 -delete
        for el in "${PRIMARY_PARTITION[@]}"
        do
            scp user@${FILERS_LOCATION[0]}:$dir1/t1_weekly_1680_"$el"_200003_5.data $PRIMARY/. || scp user@${FILERS_LOCATION[1]}:$dir2/t1_weekly_1680_"$el"_200003_5.data $PRIMARY/.
        done
    
        # delete first and then copy the files in secondary directory   
        find "$SECONDARY" -mindepth 1 -delete
        for sl in "${SECONDARY_PARTITION[@]}"
        do
            scp user@${FILERS_LOCATION[0]}:$dir1/t1_weekly_1680_"$sl"_200003_5.data $SECONDARY/. || scp user@${FILERS_LOCATION[1]}:$dir2/t1_weekly_1680_"$sl"_200003_5.data $SECONDARY/.
        done
    fi
    

    当我从 Python subprocess 模块-

    proc = subprocess.Popen(shell_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable='/bin/bash')
    (stdout, stderr) = proc.communicate()
    if proc.returncode != 0:
        # log an error with message which file numbers are missing in machineB and machine
    else:
        # log successfull status
    

    在我上面的shell脚本中,我使用的是管道 || 操作人员如果文件不在 机器B 然后试一下 机器C 使用管道 || 操作人员

    这是可能的吗?

    2 回复  |  直到 11 年前
        1
  •  1
  •   BMW    11 年前

    如果您需要获取文件名和现有代码,请尝试此操作,您还需要为辅助scp设置不同的现有代码,例如 exit 102

    # delete first and then copy the files in primary directory
        find "$PRIMARY" -mindepth 1 -delete
        for el in "${PRIMARY_PARTITION[@]}"
        do
            if `scp user@${FILERS_LOCATION[0]}:$dir1/t1_weekly_1680_"$el"_200003_5.data $PRIMARY/. || scp user@${FILERS_LOCATION[1]}:$dir2/t1_weekly_1680_"$el"_200003_5.data $PRIMARY/. ` ; then
                :
            else
                echo " scp is not successful on file $dir1/t1_weekly_1680_${el}_200003_5.data"
                exit 101
        done
    
        2
  •  0
  •   Ritesh Prajapati    11 年前

    您可以使用

    退出$?

    退出$LINENO

    使用非成功代码退出shell脚本。