Bash
Bash 腳本手動執行,但在 crontab 上失敗
我是 shell 腳本的新手。我編寫了一個shell腳本來對MySQL數據庫進行增量備份。該腳本是可執行格式,手動執行時執行成功,但通過crontab執行時失敗。
*crontab 入口是這樣的: /1 * * * * /home/db-backup/mysqlbackup.sh
下面是shell腳本程式碼 -
#!/bin/sh MyUSER="root" # USERNAME MyPASS="password" # PASSWORD MyHOST="localhost" # Hostname Password="" #Linux Password MYSQL="$(which mysql)" if [ -z "$MYSQL" ]; then echo "Error: MYSQL not found" exit 1 fi MYSQLADMIN="$(which mysqladmin)" if [ -z "$MYSQLADMIN" ]; then echo "Error: MYSQLADMIN not found" exit 1 fi CHOWN="$(which chown)" if [ -z "$CHOWN" ]; then echo "Error: CHOWN not found" exit 1 fi CHMOD="$(which chmod)" if [ -z "$CHMOD" ]; then echo "Error: CHMOD not found" exit 1 fi GZIP="$(which gzip)" if [ -z "$GZIP" ]; then echo "Error: GZIP not found" exit 1 fi CP="$(which cp)" if [ -z "$CP" ]; then echo "Error: CP not found" exit 1 fi MV="$(which mv)" if [ -z "$MV" ]; then echo "Error: MV not found" exit 1 fi RM="$(which rm)" if [ -z "$RM" ]; then echo "Error: RM not found" exit 1 fi RSYNC="$(which rsync)" if [ -z "$RSYNC" ]; then echo "Error: RSYNC not found" exit 1 fi MYSQLBINLOG="$(which mysqlbinlog)" if [ -z "$MYSQLBINLOG" ]; then echo "Error: MYSQLBINLOG not found" exit 1 fi # Get data in dd-mm-yyyy format NOW="$(date +"%d-%m-%Y-%T")" DEST="/home/db-backup" mkdir $DEST/Increment_backup.$NOW LATEST=$DEST/Increment_backup.$NOW $MYSQLADMIN -u$MyUSER -p$MyPASS flush-logs newestlog=`ls -d /usr/local/mysql/data/mysql-bin.?????? | sed 's/^.*\.//' | sort -g | tail -n 1` echo $newestlog for file in `ls /usr/local/mysql/data/mysql-bin.??????` do if [ "/usr/local/mysql/data/mysql-bin.$newestlog" != "$file" ]; then echo $file $CP "$file" $LATEST fi done for file1 in `ls $LATEST/mysql-bin.??????` do $MYSQLBINLOG $file1>$file1.$NOW.sql $GZIP -9 "$file1.$NOW.sql" $RM "$file1" done $RSYNC -avz $LATEST /home/rsync-back
- 首先,當安排在 crontab 上時,它沒有顯示任何錯誤。我怎樣才能知道腳本是否正在執行?
- 其次,在 crontab 中執行 shell 腳本的正確方法是什麼。
- 一些部落格建議更改環境變數。什麼是最好的解決方案
從 crontab 執行的腳本並不總是具有您通常認為理所當然的相同環境變數…執行以下操作:
改變
#!/bin/sh
到
#!/bin/sh -x
使用 -x,您可以嘗試手動設置 PATH,如果所有其他方法都失敗,甚至可以啟動 /etc/profile。
#!/bin/sh -x PATH=/bin:/sbin:/usr/bin:/usr/sbin /bin/sh /etc/profile
/bin/sh 版本的 shell 不喜歡 $(…) 構造。您最好的選擇是執行以下操作之一:
將 shebang 行更改為 #!/bin/bash
將 crontab 命令更改為 */1 * * * * /bin/bash /home/db-backup/mysqlbackup .sh
1 和 2。