Applying commands recursively through a directory tree

There are many times when it is necessary to execute commands recursively. That is, you may need to repeat a command throughout all the branches of a directory tree. Recursive execution is very useful but also can be dangerous. It gives a single interactive command the power to operate over a much broader range of your system than your current directory, and the appropriate caution is necessary. Think twice before using these capabilities, particularly when operating as the superuser.

Some of the GNU commands on Linux systems have built-in recursive capabilities as an option. For example, chmod modifies permissions on files in the current directory:

$ chmod g+w *.c

In this example, all files with the .c extension in the current directory are given the group-write permission. However, there may be a number of directories and files in hierarchies that require this change. chmod contains the -R option (note the uppercase option letter; you may also use --recursive), which instructs the command to operate not only on files and directories specified on the command line, but also on all files and directories contained beneath the specified directories. For example, this command gives the group-write permission to all files in a source-code tree named /home/adam/src:

$ chmod -R g+w /home/adam/src

Provided you have the correct privileges, this command will descend into each subdirectory in the src directory and add the requested permission ...

Get LPI Linux Certification in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.