出现SSH偶尔出现的bug通常会导致Bash脚本运行失败。解决这种问题的方法是使用SSH连接选项和前置测试(pre-flight checks)。以下是一个解决方案的示例:
#!/bin/bash
# Server Configuration
server="example.com"
username="user"
remote_path="/home/user/remote_folder"
# Local Configuration
local_path="/backup"
backup_name="backup.tar.gz"
# SSH connection options
ssh_options="-o ConnectTimeout=5"
# Pre-flight checks
if [[ ! -d "${local_path}" ]]; then
echo "Local path ${local_path} does not exist"
exit 1
fi
if ssh ${ssh_options} "${username}@${server}" [[ ! -d "${remote_path}" ]]; then
echo "Remote path ${remote_path} does not exist"
exit 1
fi
# Backup files
tar -zcf "${local_path}/${backup_name}" /path/to/files
# Transfer files to remote server
scp ${ssh_options} "${local_path}/${backup_name}" "${username}@${server}:${remote_path}"
if [[ $? -ne 0 ]]; then
echo "Error transferring files"
exit 1
fi
# Clean up local backups
rm "${local_path}/${backup_name}"
此示例脚本包含前置测试以确保本地文件夹和远程文件夹存在。使用SSH连接选项可以强制设置超时并提高脚本的稳定性。如果从本地计算机到远程服务器的文件传输失败,则脚本将退出并显示错误消息。
上一篇:Bash脚本代码运行但不返回数据