toop
toop

Reputation: 11294

bash - delete list of directories (including their contents)

The below script gives this error:

rm: illegal option -- 4
rm: illegal option -- 5
rm: illegal option -- 4
rm: illegal option -- 3
rm: illegal option -- 2

the script:

#!/bin/bash
keep_no=$1+1
cd "/mydirec/"
rm -rf `ls | sort -nr | tail +$keep_no`

I would like the script to accept an argument (of num of direcs to keep) then remove all directories (including their containing files) except for the (number passed in the script - ordering by the numerical direc names in descending order).

ie if /mydirec/ contains these direc names:

53
92
8
152
77

and the script is called like: bash del.sh 2

then /mydirec/ should contains these direcs (as it removes those that aren't the top 2 in desc order):

152
92

Can someone please help with the syntax?

Upvotes: 2

Views: 4657

Answers (3)

onur güngör
onur güngör

Reputation: 715

Should read:

rm -rf `ls | sort -nr | tail -n +$keep_no`

But it is good practice not to parse ls output. Use find instead.

#!/bin/bash
keep_no=$(( $1+1 ))
directory="./mydirec/"
cd $directory
rm -rf `find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n'| sort -nr | tail -n +$keep_no`
cd -

Upvotes: 5

4ndrew
4ndrew

Reputation: 16212

If you want to leave two directories (not to delete) you need to calculate total number of directories. And xargs utility is more convenient way to pass a list of arguments to rm.

#!/bin/bash
dir="/yourdir"
total_no=`ls | wc -l`
keep_no=$(( $total_no - $1 ))
ls | sort -nr | tail -n $keep_no | xargs rm -rf

Upvotes: 0

kubanczyk
kubanczyk

Reputation: 5941

#!/bin/bash
if [[ -z "$1" ]]; then 
   echo "syntax is..."
   exit 1
fi
keep_no=$(( $1 + 1 ))
cd "/mydirec/"
IFS='
';    # record separator: only enter inside single quotes
echo rm -rf $(ls | sort -nr | tail +$keep_no)

Verify the output of the script manually, then execute the script through sh:

./your_script.sh | sh -x

Upvotes: 5

Related Questions