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
  • 66,199
  • 35
  • 114
  • 250
Saith
  • 15
  • 3

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
  • 66,199
  • 35
  • 114
  • 250
  • 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](https://unix.stackexchange.com/a/401782/265604), usernames should not contain spaces. –  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
  • They're anywhere the administrator wants them to be. The [Filesystem Hierarchy Standard](http://www.pathname.com/fhs/pub/fhs-2.3.html#HOMEUSERHOMEDIRECTORIES) says: "/home is a fairly standard concept, but it is clearly a site-specific filesystem. [9] The setup will differ from host to host. Therefore, no program should rely on this location. [10]" – Jeff Schaller Jan 15 '18 at 21:04
  • 1
    Agreed that `username` may not have spaces, but `/ho me/` (or its substitute) might. – Jeff Schaller Jan 15 '18 at 21:25
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
  • 866
  • 2
  • 9
  • 20