我编写了一个脚本,用于将文件从一台服务器传输到另一台服务器。
首先,我在一台服务器上创建所有压缩文件的tar,然后将tar转移到另一台服务器。
成功转移后,我在服务器上进行文件解压缩。
我需要知道一件事,如果无论如何tar文件损坏传输失败,我如何使用Unix TRAP功能处理Restartability和Errors。
如果存在任何错误,我需要将执行恢复到初始状态。
下面提到的是我脚本中的一小段代码
tar -cvf files_to_send.tar *.txt -C ${1}
RC=$?
if [ ${RC} -ne 0 ]; then
echo "Unable to Create Tar files of received files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
return 1
fi
cd ${1}
gzip files_to_send.tar
RC=$?
if [ ${RC} -ne 0 ]; then
echo "Unable to Create Zip of tar files" >> ${LOG_FILE}
echo "Deleting End Files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
echo "Deleting tar file" >> ${LOG_FILE}
rm -f ${1}/files_to_send.tar >> ${LOG_FILE}
return 1
fi
cd ${1}
chmod 775 files_to_send.tar.gz >> ${LOG_FILE}
RC=$?
if [ ${RC} -ne 0 ]; then
echo "Unable to change permissions of tar and end files" > ${LOG_FILE}
echo "Deleting End Files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
echo "Deleting Zipped tar file" >> ${LOG_FILE}
rm -f ${SOURCE_DIR}/files_to_send.tar.gz >> ${LOG_FILE}
return 1
答案 0 :(得分:1)
您可以这样做:
trap 'do_something' ERR # start special error handling
tar ... # if the command fails, do_something will be executed
trap - ERR # stopping special error handling
do_something
可以是函数,命令或脚本。
但如果你正确处理错误案例,你甚至不需要trap
。我用布尔逻辑编写了一个脚本版本,无需将返回代码存储在变量中,请参阅:
if tar -cvf files_to_send.tar *.txt -C ${1}; then
echo "Unable to Create Tar files of received files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
return 1
fi
cd ${1}
if gzip files_to_send.tar; then
echo "Unable to Create Zip of tar files" >> ${LOG_FILE}
echo "Deleting End Files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
echo "Deleting tar file" >> ${LOG_FILE}
rm -f ${1}/files_to_send.tar >> ${LOG_FILE}
return 1
fi
cd ${1}
if chmod 775 files_to_send.tar.gz >> ${LOG_FILE}; then
echo "Unable to change permissions of tar and end files" > ${LOG_FILE}
echo "Deleting End Files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
echo "Deleting Zipped tar file" >> ${LOG_FILE}
rm -f ${SOURCE_DIR}/files_to_send.tar.gz >> ${LOG_FILE}
return 1
fi