我是初学者。
这是我创建的shell脚本,它驻留在生产服务器上。目标是使用登台/测试服务器上的内容刷新我的生产Drupal内容。
工作原理: 它进入测试/登台服务器,执行我的Drupal内容数据库的mysqldump,然后转储到生产中的临时文件夹的SCP。从那里,它需要备份当前生产Drupal内容数据库(再次通过mysqldump),然后使用来自登台服务器的转储刷新生产内容数据库。
我的问题: 虽然我知道如何编写脚本来执行命令,但我不清楚在下一个命令执行之前如何实现错误检查(例如,检查返回代码?)。
#!/bin/bash
#
# Name: drupal_dump.sh
# Developer: Michael Paul
# Created: 2014-03-21
# Last updated: 2014-04-28
# Description:
# 1. Remotes into Test server, runs a script to take a dump of Drupal content DB.
# 2. Copies (scp) that dump to Prod
# 3. Takes backup of current prod Drupal content DB
# 4. Overwrites current prod Drupal content DB with the one from Test
#
# If needed, issue the following command to restore the production backup:
# mysql -p -u root myDrupalDatabase < path/to/backupfile.sql
REMOTEHOST=xx.xxx.xx.xxx
REMOTEUSER=myRemoteUsername
DUMPDIR=~/sqldumps
DESTDIR=~/incoming
BACKUPSDIR=~/backups
LOGSDIR=~/logs
TIMESTAMP="`date '+%Y%m%d_%H%M%S'`"
DUMPFILE="mysqldump_stage_${TIMESTAMP}.sql"
PRODBACKUPFILE="mysqldump_prod_${TIMESTAMP}.sql"
# Remote into Test server, backup Drupal database
echo "Creating dump file on Test server..."
ssh -i ~/.ssh/myRemoteServer.pem $REMOTEUSER@$REMOTEHOST "mysqldump --routines -u root --password= myDrupalDatabase > $DUMPDIR/$DUMPFILE && exit"
echo "Dump file created at $DUMPDIR/$DUMPFILE"
# Copy that dump to Prod
echo "Copying Test dump file to $DESTDIR on Prod..."
scp -i ~/.ssh/myRemoteServer.pem $REMOTEUSER@$REMOTEHOST:$DUMPDIR/$DUMPFILE $DESTDIR
echo "File has been copied to $DESTDIR/$DUMPFILE on Prod."
# Backup current Prod Drupal content DB
echo "Backing up current Production Drupal content database..."
mysqldump --routines -u root --password= myDrupalDatabase > $BACKUPSDIR/$PRODBACKUPFILE
echo "File backed up as $BACKUPSDIR/$PRODBACKUPFILE"
# Overwrite current Prod Drupal content DB with that taken from Test
echo "Updating Production database with content from Test..."
mysql -p -u root --password= myDrupalDatabase < $DESTDIR/$DUMPFILE
echo "Update complete."
答案 0 :(得分:2)
最后一个命令的返回码存储在变量$?
中。成功定义为0
,其他任何内容都取决于程序。
scp -i ~/.ssh/myRemoteServer.pem $REMOTEUSER@$REMOTEHOST:$DUMPDIR/$DUMPFILE $DESTDIR
if [ $? -ne 0 ]; then
echo "Some sort of error message."
exit 1
fi
您也可以跳过[
/ test
实用程序并直接在if
语句中调用命令,如下所示:
if grep -q foo bar.txt; then
echo "found foo!"
else
echo "no foo!"
exit 1
fi