How do I make this script search through all users' home folders and then rm -f the files matching EXT? Right now it's only deleting the files matching EXT in the current folder where I am executing the script.

for i in *; do
  if [ "${i}" != "${i%.${EXT}}" ];then
    echo "I do something with the file $i"
    rm -f $i

Use bash's globstar option to recurse for you:

EXT=csv             ## for example
shopt -s globstar failglob
rm -f /home/**/*."$EXT"

(Assuming all your user's home directories are under /home). I've also set failglob so that if there are no matching files, the rm command is not run.

More generally, you could pull up your user's home directories with a shell loop:

shopt -s globstar failglob
for homedir in $(getent passwd | awk -F: '$3 >= 500 { print $6 }'|sort -u)
  rm -f "$homedir"/**/*."$EXT"

This runs on the assumption that you don't have any user home directories with spaces, tabs, or newlines in them.

| improve this answer | |
  • Thanks! How would that fit into the first script I posted above? – Saith Jan 15 '18 at 17:51
  • I would consider replacing it, depending on what extensions you're interested in -- you could loop over them as well. – Jeff Schaller Jan 15 '18 at 17:56
  • @JeffSchaller According to this, usernames should not contain spaces. – Isaac Jan 15 '18 at 20:45
  • @isaac It wouldn’t be the usernames, as I’m printing the home directories. I’ve never seen a home directory with a space in it, but it’s possible. – Jeff Schaller Jan 15 '18 at 20:58
  • 1
    Agreed that username may not have spaces, but /ho me/ (or its substitute) might. – Jeff Schaller Jan 15 '18 at 21:25

To test:

find /home/ -name '*.txt' -exec ls -l {} \;

To actually remove:

find /home/ -name '*.txt' -exec rm -f {} \;

Of course replace 'txt' with what you need.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.