2012-09-01 153 views
3

我正在创建一个简单的脚本,它将帮助我的Ubuntu服务器管理我的备份。我每隔x个小时从本地机器压缩文档,并将其转移到备份机器。我想要有最大数量的备份可以保留在我的备份目录中。我正在编写一个脚本,如果已达到最大数量的备份,它将删除较早的备份。这是我迄今为止所做的,当我运行脚本时它会生成一个名为MAX_backups的文件。任何想法为什么这个文件正在创建?在bash编程方面,我的经验非常丰富,但任何帮助都将不胜感激。谢谢。Bash脚本创建意外文件

#!/bin/bash 

backup_count=$(ls ~/backup | wc -w) 

MAX_backups='750' 

extra_count=$((backup_count - MAX_backups)) 

if [ backup_count > MAX_backups ] 
then 
     for ((i=0; i <= extra_count; i++)) 
     do 
       file=$(ls ~/backup -t -r -1 | head --lines 1) 
       rm ~/backup/"$file" 
     done 
fi 

回答

7
if [ backup_count > MAX_backups ] 

>该被解释为一个文件重定向。尝试下列操作之一:

# ((...)) is best for arithmetic comparisons. It is parsed specially by the shell and so a 
# raw `>` is fine, unlike within `[ ... ]` which does not get special parsing. 
if ((backup_count > MAX_backups)) 

# [[ ... ]] is a smarter, fancier improvement over single brackets. The arithmetic operator 
# is `-gt`, not `>`. 
if [[ $backup_count -gt $MAX_backups ]] 

# [ ... ] is the oldest, though most portable, syntax. Avoid it in new bash scripts as you 
# have to worry about properly quoting variables, among other annoyances. 
if [ "$backup_count" -gt "$MAX_backups" ] 
+0

这是完美的!非常感谢你的帮助。 – Kyle

0

不知道为什么文件被创建,但我会想你的“测试”的版本(括号运算符if语句)创建此文件。 我觉得比较应该改成

if [ $backup_count -gt $MAX_backups ] 

编辑:当然!我错过了文件重定向,这就是创建文件的原因。