Link to home
Start Free TrialLog in
Avatar of enthuguy
enthuguyFlag for Australia

asked on

how to get directory names in a list and perform rm safely using shell

Hi,
would request your advise on this pls

I have a couple of directories with bunch of sub directories in date format

eg.
directory name :
/u01/app/date_list/2016-09-10
/u01/app/date_list/2016-09-11
/u01/app/date_list/2016-09-12
/u01/app/date_list/2016-09-13
/u01/app/date_list/2016-09-14
/u01/app/date_list/2016-09-15

would like to delete some directories by accepting date range in comma separated and delete only those directories.
e.g 2016-09-11,2016-09-13,2016-09-15

so outcome after delete would be
/u01/app/date_list/2016-09-10
/u01/app/date_list/2016-09-12
/u01/app/date_list/2016-09-14

I can hard code the base directory to be safe e.g

date_range=$1
base_dir=/u01/app/date_list
 for currentDt in $(echo ${date_range} | sed "s/,/ /g")
do
	if ([ "${currentDt}" != "" ] || [ "${currentDt}" != "*" ]); then
		# is this enough? or can we add some more validation ?
		# rm -Rf  ${base_dir}/${currentDt}
	fi
done

Open in new window



pls help is there any strong validation that I can perform. or a better way to handle this.

thanks in advance
Avatar of Joseph Gan
Joseph Gan
Flag of Australia image

You can use "rsync" to do this if you like:

Similar to this https://www.experts-exchange.com/questions/28963539/Unix-How-to-Bulk-Remove-Multiple-Directories-from-FileSystem.html


mkdir empty_dir

for date in 2016-09-11 2016-09-13 2016-09-15 ...

do

rsync -a --delete empty_dir /u01/app/date_pist/$date

done
Three points for you:

1) Your logic is flawed - you need use '&&' instead of '||'
2) You can use the -d test to ensure you are targeting a directory.
3) Instead of piping your input through sed, use the variable substitution ${var//Pattern/Replacement}, such as ${currentDt//,/ }

Also, instead of sed/substitution, you could just create a loop to read $1, act on it, then shift to the next entry.  This would require you to use a space delimiter on the command line, but should otherwise work the same.
SOLUTION
Avatar of Insoftservice inso
Insoftservice inso
Flag of India 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
SOLUTION
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
ASKER CERTIFIED SOLUTION
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 enthuguy

ASKER

thanks al
Worked well