1

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.

#!/bin/bash
EXT=jpg
for i in *; do
  if [ "${i}" != "${i%.${EXT}}" ];then
    echo "I do something with the file $i"
    rm -f $i
  fi
done
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Saith
  • 15

2 Answers2

4

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)
do
  rm -f "$homedir"/**/*."$EXT"
done

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

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
0

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.

Putnik
  • 886