System Administration & Network Administration
bash grep
Updated Fri, 12 Aug 2022 11:12:22 GMT

grep/list bash recursive


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.




Solution

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





Comments (2)

  • +0 – Would -print and -delete work in place of your -exec's? — Dec 21, 2010 at 20:48  
  • +0 – 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. — Dec 21, 2010 at 20:58