3

I am creating a simple script that will help my Ubuntu-Server manage my backups. I compress my documents from my local machine every x-hours and scp it over to my backup machine. I want to have a maximum amount of backups that can stay in my backup directory. I am writing a script that will delete older backups if the maximum amount of backups have been reached. This is what I have so far, and it's generating a file called MAX_backups when I run the script. Any ideas why this file is being created? I am very far from experienced when it comes to bash programming, but any help would be greatly appreciated. Thanks.

#!/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

2 Answers 2

7
if [ backup_count > MAX_backups ]

The > is being interpreted as a file redirection. Try one of these:

# ((...)) 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" ]
Sign up to request clarification or add additional context in comments.

Comments

0

Not sure why the file is created, but I would suppose your version of 'test' (the bracket operator in the if statement) creates this file. I think, the comparison should be changed to

if [ $backup_count -gt $MAX_backups ]

Edit: Of course! I missed the file redirection, this is why the file is created.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.