我的以下是一个bash脚本,我需要能够在一行上运行
### Setup dump directory ###
BAKRSNROOT=/.snapshots/tmp
#####################################
### ----[ No Editing below ]------###
#####################################
### Default time format ###
TIME_FORMAT='%H_%M_%S%P'
### Make a backup ###
backup_mysql_rsnapshot(){
local DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
local db="";
[ ! -d $BAKRSNROOT ] && ${MKDIR} -p $BAKRSNROOT
${RM} -f $BAKRSNROOT/* >/dev/null 2>&1
# [ $VERBOSE -eq 1 ] && echo "*** Dumping MySQL Database ***"
# [ $VERBOSE -eq 1 ] && echo -n "Database> "
for db in $DBS
do
local tTime=$(date +"${TIME_FORMAT}")
local FILE="${BAKRSNROOT}/${db}.${tTime}.gz"
# [ $VERBOSE -eq 1 ] && echo -n "$db.."
${MYSQLDUMP} --single-transaction -u ${MUSER} -h ${MHOST} -p${MPASS} $db | ${GZIP} -9 > $FILE
done
# [ $VERBOSE -eq 1 ] && echo ""
# [ $VERBOSE -eq 1 ] && echo "*** Backup done [ files wrote to $BAKRSNROOT] ***"
}
### Die on demand with message ###
die(){
echo "$@"
exit 999
}
我感到困惑的是,我可以写一下:
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"; for db in $DBS do mysqldump...morecode here
或者那是不可能的?我需要能够在一行中执行此操作。
答案 0 :(得分:1)
是,你可以做到。
参见我的例子:
~$ mysql -uroot -proot -Bse 'show databases'
information_schema
Company
UpdatedStructure
bd9199ce_7ccf_11e1_a561_3860779d10f7_db
checking
checkk
db_nagiosql_v32
demo
june14
mahi
midnms
mysql
现在我将此输出存储在数组中:
:~$ mydbs="$(mysql -uroot -proot -Bse 'show databases')"
这实际上是有效的:
:~$ for db in $mydbs; do echo $db;done;
information_schema
Company
UpdatedStructure
bd9199ce_7ccf_11e1_a561_3860779d10f7_db
checking
checkk
db_nagiosql_v32
demo
june14
mahi
midnms
mysql
代替for db in $mydbs; do echo "$db"; done;
你可以这样写:
for db in $mydbs; do mysqldump -uroot -proot "$db" > "$db.sql" ; done;
一行:
$ DBs="$(mysql -uroot -proot -Bse 'show databases')" ; for db in $DBs; do echo $db;done;
information_schema
Company
UpdatedStructure
bd9199ce_7ccf_11e1_a561_3860779d10f7_db
checking
checkk
db_nagiosql_v32
demo
june14
mahi
midnms
mysql
你也可以这样做:
:~$ for db in $(mysql -uroot -proot -Bse 'show databases'); do echo $db; done;
答案 1 :(得分:0)
单行for循环的正确语法是:
for asdf in blah; do something; done
请注意附加的分号。