3.3.1 Single File

Here is how to run a command on one file at a time.

Action: -execdir command ;

Execute command; true if command returns zero. find takes all arguments after ‘-execdir’ to be part of the command until an argument consisting of ‘;’ is reached. It replaces the string ‘{}’ by the current file name being processed everywhere it occurs in the command. Both of these constructions need to be escaped (with a ‘\’) or quoted to protect them from expansion by the shell. The command is executed in the directory which find was searching at the time the action was executed (that is, {} will expand to a file in the local directory).

For example, to compare each C header file in or below the current directory with the file /tmp/master:

find . -name '*.h' -execdir diff -u '{}' /tmp/master ';'

If you use ‘-execdir’, you must ensure that the PATH variable contains only absolute directory names. Having an empty element in PATH or explicitly including ‘.’ (or any other non-absolute name) is insecure. GNU find will refuse to run if you use ‘-execdir’ and it thinks your PATH setting is insecure. For example:

/bin:/usr/bin:

Insecure; empty path element (at the end)

:/bin:/usr/bin:/usr/local/bin

Insecure; empty path element (at the start)

/bin:/usr/bin::/usr/local/bin

Insecure; empty path element (two colons in a row)

/bin:/usr/bin:.:/usr/local/bin

Insecure; ‘.’ is a path element (. is not an absolute file name)

/bin:/usr/bin:sbin:/usr/local/bin

Insecure; ‘sbin’ is not an absolute file name

/bin:/usr/bin:/sbin:/usr/local/bin

Secure (if you control the contents of those directories and any access to them)

Another similar option, ‘-exec’ is supported, but is less secure. See Security Considerations, for a discussion of the security problems surrounding ‘-exec’.

Action: -exec command ;

This insecure variant of the ‘-execdir’ action is specified by POSIX. Like ‘-execdir command ;’ it is true if zero is returned by command. The main difference is that the command is executed in the directory from which find was invoked, meaning that ‘{}’ is expanded to a relative path starting with the name of one of the starting directories, rather than just the basename of the matched file.

While some implementations of find replace the ‘{}’ only where it appears on its own in an argument, GNU find replaces ‘{}’ wherever it appears.