Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 280
toop Avatar asked Nov 27 '25 17:11

toop


2 Answers

#!/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
like image 138
kubanczyk Avatar answered Nov 30 '25 08:11

kubanczyk


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 -
like image 20
onur güngör Avatar answered Nov 30 '25 08:11

onur güngör



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!