Link to home
Start Free TrialLog in
Avatar of Christopher Schene
Christopher ScheneFlag for United States of America

asked on

Need borne shell to delete all but last two backups

I wrote this shell scrip whose intent is to delete all but the last two files that match a particular pattern. I am attempting to set the variable $backupcnt to the number of files that match the pattern in line 4.

The script fails on line 4  with: "line 4: backupcnt: command not found" and on the while loop test: " line 6: [: -ge: unary operator expected"


#!/bin/bash
set -v -x
cd /opt/backup
backupcnt = $(ls -t -1 | grep $1_`hostname` | wc -l)

while [ $backupcnt -ge 2 ]
do
        ls -t -1 | grep $1_`hostname` > temp.txt
        echo cat temp.txt
        cat temp.txt
        echo rm `cat temp.txt | tail -1`
        rm `cat temp.txt | tail -1`
        backupcnt = $(ls -t -1 | grep $1_`hostname` | wc -l)
done
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Christopher Schene

ASKER

Perfect! Works great! Thanks for the fast response.
Avatar of Tintin
Tintin

You can simplfy the whole script to

#!/bin/bash
ls -t $1_$(hostname) | sed 'N;$!P;$!D;$d' | xargs rm

Open in new window