【问题标题】:Bash script creating an unexpected fileBash 脚本创建了一个意外的文件
【发布时间】:2012-09-01 06:13:20
【问题描述】:

我正在创建一个简单的脚本来帮助我的 Ubuntu-Server 管理我的备份。我每隔 x 小时从本地机器压缩我的文档,然后将其 scp 到我的备份机器。我希望有最大数量的备份可以保留在我的备份目录中。我正在编写一个脚本,如果已达到最大备份量,它将删除旧备份。这是我到目前为止所拥有的,当我运行脚本时它会生成一个名为 MAX_backups 的文件。任何想法为什么要创建这个文件?在 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

【问题讨论】:

    标签: file bash unix backup


    【解决方案1】:
    if [ backup_count > MAX_backups ]
    

    &gt; 被解释为文件重定向。尝试以下方法之一:

    # ((...)) 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" ]
    

    【讨论】:

    • 太完美了!非常感谢您的帮助。
    【解决方案2】:

    不确定为什么要创建该文件,但我想您的“test”版本(if 语句中的括号运算符)会创建此文件。 我认为,比较应该改为

    if [ $backup_count -gt $MAX_backups ]
    

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

    【讨论】:

      猜你喜欢
      • 2018-01-20
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多