Sometimes you want to operate or execute a command on the files that are found. 1
This is really useful. 2
There’s the -exec option that does that. 3
exec comes from execute. 4
Let's see how it works. 5
I want to see the contents of the files in the /etc directory that are modified in the last 24 hours. 6
There are two steps. 7
First, I'll find those files, find /etc -type f -mtime 0 8
OK, I always forget to run the commands as root. 9
These are the files modified on the last day. The second step is to add the -exec option and the shell 10
command 11
I want to execute on each found file. 12
I'll write the entire command and then I'll explain it to you in detail. 13
So -exec cat {} \; 14
This command will run cat on each file found by find. The cat command requires 15
as argument the file to display. 16
I do not know what name to write and 17
I'm writing a pair of curly braces. 18
In this construction 19
the pair of curly braces will expand to the file found by the find command. 20
The command after -exec ends when backslash semicolon appears; that's always there at the end, 21
the syntax of this construction. 22
I have displayed the contents of all of those files. 23
Let's do another example. 24
I want to back up or make a copy of all configuration files from /etc that were modified in 25
the last week. 26
As root I'm creating, a new directory backup in /root: mkdir /root backup. 27
And sudo find / etc -mtime 7 28
-type f - exec and the command cp, the file, the file to copy and I write a pair 29
of curly braces and the destination root backup. 30
Space, backslash, semicolon. 31
The files were copied sudo ls-l /root backup 32
OK, there is no file because I should have written -7, not 7; -7 means in the 33
last seven days, 34
so in the last week. And 7 means exactly 7 days. 35
So like this. 36
OK, there are a lot of files. 37
All these files are modified in the last week. 38
Let me explain to you what happens here: for each file found by the find command, the cp command is executed 39
Cp simply requires more arguments, at least 2: a source and the destination; the source will be the file 40
found by find or the pair of curly braces and the destination, the back up directory. 41
So the braces are in the place where the file should be. 42
Note that there is also the - OK option, which does the same is -exec, but interactively 43
as it asks the user first. If the user agrees, it runs the command that follows. 44
Otherwise it just returns false. 45
So instead of -exec, I'm writing -OK. 46
And it's asking for every file if it copies the file or not. 47
These can be very useful if you run a potentially dangerous command and want to see exactly on which 48
file the command will operate. That's all!