Solved

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

Posted on 2016-09-15
7
43 Views
Last Modified: 2016-09-28
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
0
Comment
Question by:enthuguy
7 Comments
 
LVL 16

Expert Comment

by:Joseph Gan
ID: 41800731
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
2
 
LVL 50

Expert Comment

by:Steve Bink
ID: 41800784
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.
0
 
LVL 15

Assisted Solution

by:Insoftservice
Insoftservice earned 250 total points
ID: 41803278
just provide o/p of this code . will provide u code to delete folders too
#!/bin/bash

$MYDIR="/u01/app/date_list"

DIRS=`ls -l $MYDIR | egrep '^d' | awk '{print $8}'`
# and now loop through the directories:
for DIR in $DIRS
do
echo  ${DIR}
done

Open in new window

1
Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

 
LVL 50

Assisted Solution

by:Steve Bink
Steve Bink earned 250 total points
ID: 41803342
On further reflection, I thought I'd offer one more piece of advice.  If you feel this script may be subject to abuse, you may want to include logic to check/remove any instances of '..' in the paths passed from the command line.  Even if you're hard-coding the base dir, some bad things can happen if a user can crawl through parent directories.
1
 

Accepted Solution

by:
enthuguy earned 0 total points
ID: 41813387
thanks, tried this way with all your input

#Local variables
base_dir=/oracle/data/build
current_dir=`pwd`
NONE='\033[00m'
RED='\033[01;31m'
GREEN='\033[01;32m'
YELLOW='\033[01;33m'
BOLD='\033[1m'
BLUE='\033[01;34m'

if [ "${R16_3}" == "true" ]; then
# Trim blank spaces
  date_range=`echo ${R16_3_DATES//[[:blank:]]/}`
  if ([ ! -z "${date_range}" ] || [ "${date_range}" != "*" ]) || [ "${date_range}" == "" ]
  then
    for currentDt in $(echo ${date_range} | sed "s/,/ /g")
    do
      if [ "`date '+%Y-%m-%d' -d ${currentDt} 2>/dev/null`" = "${currentDt}" ]
      then
        echo -e "${YELLOW}${BOLD}rm -Rf  ${base_dir}/R16_3/${currentDt}${NONE}"
        if [ -d "${base_dir}/R16_3/${currentDt}" ]; then
           rm -Rf  "${base_dir}/R16_3/${currentDt}"
        fi
      else
        echo -e "${RED}${BOLD}Invalid date : ${base_dir}/${currentDt}. Pls ensure you provide valid date.${NONE}"
      fi
    done
  else
    echo -e "${RED}${BOLD}Invalid date : ${base_dir}/${date_range}. Pls ensure you provide valid date.${NONE}"
  fi
fi

Open in new window

0
 

Author Comment

by:enthuguy
ID: 41813389
thanks al
0
 

Author Closing Comment

by:enthuguy
ID: 41819442
Worked well
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Little introduction about CP: CP is a command on linux that use to copy files and folder from one location to another location. Example usage of CP as follow: cp /myfoder /pathto/destination/folder/ cp abc.tar.gz /pathto/destination/folder/ab…
Utilizing an array to gracefully append to a list of EmailAddresses
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…
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.

947 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now