Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script creating an unexpected file

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
like image 294
Kyle Avatar asked Mar 07 '26 02:03

Kyle


1 Answers

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" ]
like image 59
John Kugelman Avatar answered Mar 09 '26 17:03

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!