1

我的以下是我需要能够在一行上运行的 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

或者那不可能?我需要能够在一行中执行此操作。

4

2 回答 2

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;
于 2012-12-21T07:27:37.223 回答
0

单行 for 循环的正确语法是:

for asdf in blah; do something; done

注意额外的分号。

于 2012-12-21T07:27:51.673 回答