1
parts = grep "/root/backups/*"

for part in $parts
do
    echo $part
    rm -rf $part #delete
done

I basically need to iterate through a folder and return every item in the folder using a Bash script.

Unable to get working via grep, although may be a much simpler way. First line is pure pseudo-no-clue-code.

James
  • 171
  • 1
  • 3
  • 15

4 Answers4

3

This can easily be done without looping.

If you just want to get rid of the files, just use rm:

$ rm -rf /root/backups/*

If you want to show the filenames as you delete them, use find instead:

$ find /root/backups -maxdepth 1 -mindepth 1 -print -exec rm -rf {} \;

The -maxdepth option tells find to not descend any further than one level from the starting point, /root/backups. The -mindepth option tells find where to start returning results, effectively telling find to ignore the the starting point. The -print option just prints the found files to the screen. With the -exec, the {} are replaced with the found files, so this calls rm to delete them.

EDIT: eliminated an unnecessary -exec per comment

SethG
  • 314
  • 1
  • 3
  • 7
  • Would -print and -delete work in place of your -exec's? – Aaron Copley Dec 21 '10 at 20:48
  • You could use -print to replace the first -exec, but -delete will not work on directories that are not already empty. I think you'll still need the second -exec. – SethG Dec 21 '10 at 20:58
1

Change the grep command to:

for i in ``ls -bRC1 /path/* ; do echo $i ; rm $i ; done

The -b will escape spaces and other characters that may result in errors and unintended consequences with the rm. -R is recursive. -C1 is single column (which may be redundant). I would reconsider the -rf

You may want to use find instead of a for loop

find /path -H -maxdepth 3 -type f -mtime +7 -exec rm {} \; -ls

If you don't know what the above options mean, type man find.

PaulR
  • 251
  • 1
  • 2
  • `for i in /path/*` does everything except the recursion and works with filenames that have spaces. Here is some information regarding [avoiding parsing `ls`](http://mywiki.wooledge.org/ParsingLs). – Dennis Williamson Dec 22 '10 at 00:52
0

grep -l will give you just the filenames

parts = grep -rl ....

silviud
  • 2,687
  • 2
  • 18
  • 19
0

You want a list of file names in a given directory. There is a program that does this, and you be embarrassed to read it's name: ls. Thats all it does! You want a recursive listing including files in subdirectories, so use ls -R. You can put the output of that into a variable in your script and do as you please with it.

jldugger
  • 14,342
  • 20
  • 77
  • 129