![为什么使用 bash -x script.sh 启动时,我的 bash 脚本输出“+ '[' 0 -le 1 ']'”?](https://linux22.com/image/1013200/%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BD%BF%E7%94%A8%20bash%20-x%20script.sh%20%E5%90%AF%E5%8A%A8%E6%97%B6%EF%BC%8C%E6%88%91%E7%9A%84%20bash%20%E8%84%9A%E6%9C%AC%E8%BE%93%E5%87%BA%E2%80%9C%2B%20'%5B'%200%20-le%201%20'%5D'%E2%80%9D%EF%BC%9F.png)
我创建了以下 shell 脚本来备份 MySQL DB、对其进行压缩,然后将其复制到 s3 存储桶:
#vim /home/ubuntu/backup/mysqlbackup2.sh
#!/bin/bash
## Backup mysql DB, zip it and then copy it to s3 bucket
mysqldump -hhostname -uusername dbName -p'p@ssW0rd' > db.sql
if [ $? -le 1 ]
then
# zip the file and copy it s3 bucket
sudo gzip -9 db.sql
s3cmd put db.sql.gz s://mys3bucket/
else
echo "Fail to backup MySQL DB" >> "backup.log"
fi
一切正常,备份已复制到 S3 存储桶。但我无法理解 shell 脚本的输出:
我理解密码警告,但为什么会显示:'[' 0 -le 1 ']'
?我的 if 条件有什么问题吗?
答案1
您的脚本:
mysqldump -hhostname -uusername dbName -p'p@ssW0rd' > db.sql
if [ $? -lt 1 ] #<-- if the script exit status value is less than or equal 1, which means it succeeded then execute the if block
then
# zip the file and copy it s3 bucket
gzip -9 db.sql #<-- create a zipped folder from the mysql backup file
s3cmd put db.sql.gz s://mys3bucket/ #<-- Amazon http request PUT command
else
echo "Fail to backup MySQL DB" >> "backup.log" #<-- if the backup failed let us know by out putting this message into the backup.log file
fi
'[' 0 -le 1 ']'
:这里的零表示备份命令成功,读作“小于或等于”。是的,带有“+”的那些行向您显示了执行过程中的各个步骤,这是因为您-x
在执行 bash 脚本时使用了选项。
另外,正如 desert 所指出的,应该删除 sudo 和“-le”选项,并将其分别更改为“-lt”。