Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Need borne shell to delete all but last two backups

Posted on 2012-04-11
3
Medium Priority
?
415 Views
Last Modified: 2012-04-12
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
0
Comment
Question by:Christopher Schene
3 Comments
 
LVL 85

Accepted Solution

by:
ozo earned 2000 total points
ID: 37836100
backupcnt=$(ls -t -1 | grep $1_`hostname` | wc -l)
0
 

Author Closing Comment

by:Christopher Schene
ID: 37836217
Perfect! Works great! Thanks for the fast response.
0
 
LVL 48

Expert Comment

by:Tintin
ID: 37836389
You can simplfy the whole script to

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

Open in new window

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Background Still having to process all these year-end "csv" files received from all these sources (including Government entities), sometimes we have the need to examine the contents due to data error, etc... As a "Unix" shop, our only readily …
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Suggested Courses
Course of the Month11 days, 7 hours left to enroll

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question