如何在子shell中设置变量?

How to set variables in a subshell?

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

脚本将从本地数据中心复制文件 local_dc 但如果它关闭或没有响应,那么它将从远程数据中心复制相同的文件 remote_dc_1 如果它也关闭,那么它将从另一个远程数据中心复制相同的文件 remote_dc_2,如下所示。

现在假设如果 local_dc 机器出现故障,那么它将从 remote_dc_1 机器复制文件所以我需要发送一封电子邮件说这台机器出现故障所以从其他远程机器复制。如果 local_dc 机器出现故障,我不想发送多封电子邮件,所以我在最后发送电子邮件,这样我只收到一封电子邮件,而不是每个文件收到多封电子邮件。

下面是我的脚本-

do_Copy() {
  el=
  PRIMSEC=
  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 做错了什么吗?

您无法使用 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=
  PRIMSEC=
  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."