Total Hit Counter

Tuesday, October 23, 2012

Find examples with exec command


Search files with find and delete them with exec, this is probably one of the most common actions with exec, and you should not use exec for this, read later, here are some examples of common uses:

1) List all files starts with “abc”:
 find / -name "abc*" -exec /bin/ls {} \;

2) Search all files start with “abc” and delete them:
 find / -name "abc*" -exec /bin/rm {} \;
3) Search all files with size > of 10 MB and delete them:
 find / -size +10M -exec /bin/rm {} \;
Sometimes some programs goes wild and create thousands of small files into one directoy, in this case you cannot use a simple rm * because the shell would not be able to manages the expansion of the character * with all these file names, but you can use find to delete all files in a directory one by one.
 find . -exec /bin/rm {} \;
You should NOT use these examples, In newer verison you will find the option -delete which is safer then “-exec /bin/rm {} ;”. For example:
find / -name "*.old" -delete
In older Unix system you could not have the -delete option, and so you have no choice but to use the -exec action.
4) To change permissions on files recursively, leave directories alone.
find ./ -type f -exec chmod 755 {} \;
5) With the option -type f you select only the files and after that is easy to do a chmod on them. Recursively change the ownership of all the files from old user to new user
find / -user test_old  -type f  -exec chown  test_new {} \;

6) Recursively change the permissions of all, and only, the directory
find . -type d -exec chmod 655 {} \;
In this example I’ve used again the option -type with d parameter to identify only the directories.

No comments: