备份bash脚本出错:意外令牌“换行符”

时间:2017-03-09 10:00:51

标签: bash backup

我在处理备份的bash脚本上遇到问题:每日,每月,每年。这是脚本:

#!/bin/bash

echo > /home/alpha/folder/keep.txt
#writing dates of the backups that should be kept to the array

for i in {0..7}; do ((keep[$(date +%Y%m%d -d "-$i day")]++)); done
for i in {0..4}; do ((keep[$(date +%Y%m%d -d "sunday-$((i+1)) week")]++)); done
for i in {0..12}; do
        DW=$(($(date +%-W)-$(date -d $(date -d "$(date +%Y-%m-15) -$i month" +%Y-%m-01) +%-W)))
        for (( AY=$(date -d "$(date +%Y-%m-15) -$i month" +%Y); AY < $(date +%Y); AY++ )); do
        ((DW+=$(date -d $AY-12-31 +%W)))
        done
        ((keep[$(date +%Y%m%d -d "sunday-$DW weeks")]++))
done
for i in {0..30}; do
        DW=$(date +%-W)
        for (( AY=$(($(date +%Y)-i)); AY < $(date +%Y); AY++ )); do
        ((DW+=$(date -d $AY-12-31 +%W)))
        done
        ((keep[$(date +%Y%m%d -d "sunday-$DW weeks")]++))
        done

#writing the array to file keep.txt line by line
for i in ${!keep[@]}; do echo $i >> /home/alpha/folder/keep.txt; done

#delete all files that not mentioned in keep.txt
cd /home/alpha/folder
ls -1 /home/alpha/folder/ | sort /home/alpha/folder/keep.txt /home/alpha/folder/keep.txt - | uniq -u | xargs rm -rf
rm /home/alpha/folder/keep.txt

当我尝试运行脚本时,抛出错误消息:

./back.sh: line 12: syntax error near unexpected token `newline' ./back.sh: line 12: ` done'

我在脚本上哪里做错了?

1 个答案:

答案 0 :(得分:1)

您的date表达式似乎在算术上下文中行为异常。添加临时变量为我解决了问题:

#!/bin/bash

echo > /home/alpha/folder/keep.txt
#writing dates of the backups that should be kept to the array

for i in {0..7}; do ((keep[$(date +%Y%m%d -d "-$i day")]++)); done
for i in {0..4}; do ((keep[$(date +%Y%m%d -d "sunday-$((i+1)) week")]++)); done
for i in {0..12}; do
        DW=$(($(date +%-W)-$(date -d $(date -d "$(date +%Y-%m-15) -$i month" +%Y-%m-01) +%-W)))
        begin=$(date -d "$(date +%Y-%m-15) -$i month" +%Y)
        for (( AY=begin; AY < $(date +%Y); AY++ )); do
        ((DW+=$(date -d $AY-12-31 +%W)))
        done
        ((keep[$(date +%Y%m%d -d "sunday-$DW weeks")]++))
done
for i in {0..30}; do
        DW=$(date +%-W)
        begin=$(($(date +%Y)-i))
        for (( AY=begin; AY < $(date +%Y); AY++ )); do
        ((DW+=$(date -d $AY-12-31 +%W)))
        done
        ((keep[$(date +%Y%m%d -d "sunday-$DW weeks")]++))
        done

#writing the array to file keep.txt line by line
for i in ${!keep[@]}; do echo $i >> /home/alpha/folder/keep.txt; done

#delete all files that not mentioned in keep.txt
cd /home/alpha/folder
ls -1 /home/alpha/folder/ | sort /home/alpha/folder/keep.txt /home/alpha/folder/keep.txt - | uniq -u | xargs rm -rf
rm /home/alpha/folder/keep.txt

但是,我不确定为什么表达式在算术块中行为不正常。