BASH问题,计算FOR循环数组中的变量

时间:2013-03-13 23:11:40

标签: arrays bash variables for-loop count

我遇到以下脚本的问题。由于我对BASH缺乏了解,我不是百分之百确定如何创建一个循环,使用“for”来计算数组中的变量数量并循环遍历每个变量。基本上我想要做的是让脚本计算变量$ sqldumps中的变量数量,然后为每个变量运行一个MySQL Dump(也将它们记录到数据库中)。该脚本的长版本发布在底部,但下面是一个简短的版本:

#! /usr/bin/env bash
echo -ne '\033]0;World of Clucky - Backup\007'
BINDIR="$(dirname "$(readlink -fn "$0")")"
cd "$BINDIR"
sqldumps=("lwc" "bans" "frisnuk_permissions" "jail" "imonies" "GriefP" "permissions" "showcase" "simpleclans")
#Copy MySQL Databases
echo "[`date '+%H:%M'`] Starting MySQL Backup" >> /home/clucky/MinecraftServers/backup.log
for i in ${#sqldumps[*]}
    do
        echo "     ${sqldumps[i]}" >> /home/clucky/MinecraftServers/backup.log;
        /opt/lampp/bin/mysqldump -u'root' -p'CENSORED' --skip-lock-tables ${sqldumps[i]} > /home/clucky/MinecraftServers/.backups/$timedate/MySQL/${sqldumps[i]}.sql;
    done
echo "     forum";
/opt/lampp/bin/mysqldump -u'root' -p'CENSORED' forum >> /home/clucky/MinecraftServers/.backups/$timedate/MySQL/forum.sql;
echo "[`date '+%H:%M'`] MySQL Backup Complete" >> /home/clucky/MinecraftServers/backup.log

我遇到问题的特别是:

for i in ${#sqldumps[*]}

我假设我使用了错误的语法,所以如果有人能给我正确的语法,我将不胜感激。谢谢!

#! /usr/bin/env bash
echo -ne '\033]0;World of Clucky - Backup\007'
BINDIR="$(dirname "$(readlink -fn "$0")")"
cd "$BINDIR"
timedate=`date '+%m.%d.%Y-%H:%M'`
sqldumps=("lwc" "bans" "frisnuk_permissions" "jail" "imonies" "GriefP" "permissions" "showcase" "simpleclans")
echo "-------------- `date '+%d-%B-%Y %H:%M'` --------------" >> /home/clucky/MinecraftServers/backup.log
echo "[`date '+%H:%M'`] Starting Minecraft Backup" >> /home/clucky/MinecraftServers/backup.log
mkdir -p /home/clucky/MinecraftServers/.backups/$timedate
mkdir -p /home/clucky/MinecraftServers/.backups/$timedate/MySQL
nice --adjustment=19 tar -zcpf /home/clucky/MinecraftServers/.backups/$timedate/Minecraft.tar.gz \
    --directory /home/clucky/MinecraftServers/ \
    --exclude=SkyBlockkit \
    --exclude=Tekkit \
    --exclude=Vanilla \
    --exclude=test \
    --exclude=Zflocco_LP \
    --exclude=Mortuus/plugins/dynmap/web --exclude=Mortuus/plugins/AutoSaveWorld/backups --exclude Mortuus/CraftBukkitVersion --exclude=Mortuus/orebfuscator_cache --exclude=Mortuus/plugins/#Removed --exclude=Mortuus/server.log \
    --exclude=Frisnuk/plugins/dynmap/web --exclude=Frisnuk/plugins/AutoSaveWorld/backups --exclude Frisnuk/CraftBukkitVersion --exclude=Frisnuk/orebfuscator_cache --exclude=Frisnuk/plugins/#Removed --exclude=Frisnuk/plugins/#AwaitingUpdate --exclude=Frisnuk/server.log --exclude=Frisnuk/Suwako_Moriya100 --exclude=Frisnuk/Uk_Shadow --exclude=Frisnuk/Whiteghost99 --exclude=Frisnuk/greenrangermatt \
    --exclude=dailybackup.log \
    --exclude=.backups \
    --exclude=backup.log \
    --exclude=backups.log \
    --exclude=backupscript.sh \
    --exclude=dailybackup.sh \
    --exclude=.keptbackups .
echo "[`date '+%H:%M'`] Minecraft Backup Complete" >> /home/clucky/MinecraftServers/backup.log
#Purge files 3 days old
echo "[`date '+%H:%M'`] Purging Old Backups" >> /home/clucky/MinecraftServers/backup.log
find /home/clucky/MinecraftServers/.backups* -mmin +4320 -exec rm --recursive {} \;
echo "[`date '+%H:%M'`] Purging Complete" >> /home/clucky/MinecraftServers/backup.log
#Copy MySQL Databases
echo "[`date '+%H:%M'`] Starting MySQL Backup" >> /home/clucky/MinecraftServers/backup.log
for i in ${#sqldumps[*]}
    do
        echo "     ${sqldumps[i]}" >> /home/clucky/MinecraftServers/backup.log;
        /opt/lampp/bin/mysqldump -u'root' -p'CENSORED' --skip-lock-tables ${sqldumps[i]} > /home/clucky/MinecraftServers/.backups/$timedate/MySQL/${sqldumps[i]}.sql;
    done
echo "     forum";
/opt/lampp/bin/mysqldump -u'root' -p'CENSORED' forum >> /home/clucky/MinecraftServers/.backups/$timedate/MySQL/forum.sql;
echo "[`date '+%H:%M'`] MySQL Backup Complete" >> /home/clucky/MinecraftServers/backup.log
echo "[`date '+%H:%M'`] Daily Backup Complete" >> /home/clucky/MinecraftServers/backup.log
#Read back file size
filesize=$(ls -lah /home/clucky/MinecraftServers/.backups/$timedate | awk '{ print $5}')
echo "     Total Compression Size: $filesize\n" >> /home/clucky/MinecraftServers/backup.log

感谢您的协助!

4 个答案:

答案 0 :(得分:2)

不要对数组进行索引,只需使用值:

for value in "${sqldumps[@]}"; do echo $value; done

答案 1 :(得分:2)

语法${#varname[*]}返回数组的大小,但您使用的for语法希望获得一个元素列表。所以,要么你想要:

for elem in "${varname[@]}"; do
    ... something with ${elem} ...
done

for (( i = 0; i < ${#varname[@]}; i++ )); do
    ... something with ${varname[$i]} ...
done

注意,我使用@代替*,因为它通常是对包含空格的元素的良好预防(即使在这种情况下可能不是严格必要的)。

答案 2 :(得分:0)

我冒昧地重新组织你的脚本以使其更具可读性。

#!/usr/bin/env bash

# Script starts here.
main() {
    backup_dir=~clucky/MinecraftServers
    dbs=(lwc bans frisnuk_permissions jail imonies GriefP permissions showcase simpleclans forum)

    echo -ne '\033]0;World of Clucky - Backup\007'

    log 'Starting MySQL Backup'
    dump_dbs "${dbs[@]}"
    log 'MySQL Backup Complete'
}

# Write a timestamped message to the log file.
log() {
    echo "[$(date '+%H:%M')] $*" >> "$backup_dir/backup.log"
}

# Dump each of the databases passed as an argument. The list of databases is "$@".
dump_dbs() {
    for db in "$@"; do
        # Use --skip-lock-tables for every database except "forum".
        local options=(--skip-lock-tables)
        [[ $db = forum ]] && options=()

        log "     $db"
        /opt/lampp/bin/mysqldump -u root -p CENSORED "${options[@]}" "$db" \
            > "$backup_dir/.backups/$timedate/MySQL/$db.sql"
    done
}

main "$@"

以下是我所做的一些事情:

  1. 这样的循环不会迭代数组索引,而是直接迭代每个值:

    for value in "${array[@]}"; do ...; done
    
  2. 使用~user引用用户的主目录更短。它也更安全,因为用户的主目录不一定在/home下。

  3. 将代码分解为单独的函数有助于消除一些冗余,例如反复写入backup.log的完整路径。 log()函数将带时间戳的消息行放在一个位置。

  4. forum表没有获得--skip-lock-tables选项,因此我更加明确了这一点,这样就可以摆脱重复的mysqldump行。

  5. 我从不需要的地方删除了引号。

答案 3 :(得分:0)

$i将使数组中的每个项目递增,直到它到达结尾。因此,每次在for循环中需要时,您都不必引用该数组。我也不喜欢硬编码echo,这是个人偏好,因此我将其与printf交换出来。

for i in ${#sqldumps[@]}
  do
    printf "     %s" "$i" >> /home/clucky/MinecraftServers/backup.log;
    /opt/lampp/bin/mysqldump -u'root' -p'CENSORED' --skip-lock-tables $i > /home/clucky/MinecraftServers/.backups/$timedate/MySQL/${sqldumps[i]}.sql;
done

如果您只想找到可以使用的数组大小。

Length=${#sqldumps[@]}

然后$Length将等于数组中的位数