編寫備份腳本
backupdb.sh
(這裏在根目錄下新建文件)
db_user="root"
db_password="root"
db_name="demo"
backup_dir="/backup"
time="$(date +"%Y%m%d%H%M%S")"
mysqldump -u$db_user -p$db_password $db_name | gzip > $backup_dir/$db_name"_"$time.sql.gz
賦予其執行權限:chmod u+x backupdb.sh
;
若此時直接運行./backupdb.sh
,會出現警告:
mysqldump: [Warning] Using a password on the command line interface can be insecure.
爲避免出現警告信息,可通過以下方式配置實現:
vi /etc/mysql/my.cnf
[mysqldump]
user=your_db_user_name
password=your_db_password
保存配置文件後, 再修改備份腳本,其中不需要再涉及用戶名密碼等信息。
db_name="demo"
backup_dir="/backup"
time="$(date +"%Y%m%d%H%M%S")"
mysqldump $db_name | gzip > $backup_dir/$db_name"_"$time.sql.gz
再次運行腳本,就沒有警告信息了。
創建定時任務
- Linux下Cron表達式規則:
* * * * * *
- - - - - -
| | | | | |
| | | | | + year [optional]
| | | | +----- day of week (0 - 7) (Sunday=0 or 7)
| | | +---------- month (1 - 12)
| | +--------------- day of month (1 - 31)
| +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)
- 添加計劃
# 建立計劃並執行
crontab -e
# 通過vi或其他編輯器輸入計劃, eg: 每週日0點執行
0 0 * * 0 /backupdb.sh
# 查看已有任務
crontab -l
Note:
- 如果
crontab -l
的結果爲:“no crontab for root - using an empty one”,則說明任務建立失敗; - 可通過命令
select-editor
選擇編輯器。
If you have any questions or any bugs are found, please feel free to contact me.
Your comments and suggestions are welcome!