如何在子shell中设置变量?

时间:2015-04-03 00:54:57

标签: linux bash scp gnu-parallel subshell

我有一个脚本,它将在每个服务器上运行并将某些文件复制到其中。脚本知道我在哪里运行以及我需要复制哪些文件。

脚本将从本地数据中心local_dc复制文件,但如果文件已关闭或未响应,则它将从远程数据中心remote_dc_1复制相同的文件,如果该文件也已关闭,则会复制相同的文件来自另一个远程数据中心remote_dc_2的文件,如下所示。

现在让我们说如果local_dc计算机已关闭,那么它将从remote_dc_1计算机复制文件,因此我需要发送一封电子邮件,说明此计算机已关闭,因此从其他远程计算机复制机。如果local_dc机器关闭,我不想发送多封电子邮件,所以我最后发送电子邮件,这样我每封邮件只能收到一封电子邮件,而不是多封电子邮件。

以下是我的脚本 -

do_Copy() {
  el=$1
  PRIMSEC=$2
  scp david@"$local_dc":"$dir3"/new_weekly_2014_"$el"_200003_5.data "$PRIMSEC"/. \
    || (a=1 && scp david@"$remote_dc_1":"$dir3"/new_weekly_2014_"$el"_200003_5.data "$PRIMSEC"/.) \
    || (b=2 && scp david@"$remote_dc_2":"$dir3"/new_weekly_2014_"$el"_200003_5.data "$PRIMSEC"/.) \
    || (c=3 && exit 1)
}

export -f do_Copy

parallel --retries 10 -j 10 do_Copy {} $PRIMARY ::: "${PRIMARY_PARTITION[@]}" &
parallel --retries 10 -j 10 do_Copy {} $SECONDARY ::: "${SECONDARY_PARTITION[@]}" &
wait

# problem is this doesn't work at all?
if [ $a -eq 1 ]
then
   echo "Local machine $local_dc was down, so copied from Primary Remote machine $remote_dc_1" | mailx -r "david@host.com" -s "$local_dc machine down" "david@host.com"
fi
if [ $b -eq 2 ]
then
   echo "Primary Remote machine $remote_dc_1 was down, so copied from Secondary Remote machine $remote_dc_2" | mailx -r "david@host.com" -s "$remote_dc_1 machine down" "david@host.com"
fi
if [ $c -eq 3 ]
then
   echo "All three machine's are down. Exiting out." | mailx -r "david@host.com" -s "All three machine's are down" "david@host.com"
fi

我在子shell中使用变量a,b和c做了什么错误吗?

1 个答案:

答案 0 :(得分:1)

您无法使用shell或环境变量传播此状态,但文件系统上的标志可以正常工作。

#!/bin/bash
export status_dir=$(mktemp -t -d transfer.XXXXXX)
cleanup() { rm -rf "$status_dir"; }
trap cleanup 0 # automatically clean up on exit

do_Copy() {
  el=$1
  PRIMSEC=$2
  scp david@"$local_dc":"$dir3"/new_weekly_2014_"$el"_200003_5.data "$PRIMSEC"/. \
    || { touch "$status_dir/local_down" && scp david@"$remote_dc_1":"$dir3"/new_weekly_2014_"$el"_200003_5.data "$PRIMSEC"/.; } \
    || { touch "$status_dir/primary_down" && scp david@"$remote_dc_2":"$dir3"/new_weekly_2014_"$el"_200003_5.data "$PRIMSEC"/.; } \
    || { touch "$status_dir/secondary_down"; exit 1; }
}

......以后......

[[ -e "$status_dir/local_down" ]] && \
   mailx -r "david@host.com" -s "$local_dc machine down" "david@host.com" \
     <<<"Local machine $local_dc was down, so copied from Primary Remote machine $remote_dc_1"

[[ -e "$status_dir/primary_down" ]] && \
   mailx -r "david@host.com" -s "$remote_dc_1 machine down" "david@host.com" \
     <<<"Primary Remote machine $remote_dc_1 was down, so copied from Secondary Remote machine $remote_dc_2"

[[ -e "$status_dir/secondary_down" ]] && \
   mailx -r "david@host.com" -s "All three machine's are down" "david@host.com" \
     <<<"All three machines are down. Exiting out."