Christopher Schene
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You can simplfy the whole script to
#!/bin/bash
ls -t $1_$(hostname) | sed 'N;$!P;$!D;$d' | xargs rm
ASKER