1

I understand all of this but lose it when i get to the 7th line starting with find. i don't understand the -exec cp {}. I understand that this is executing the copy command but I don't understand what the brackets{} are doing, especially if they are empty?

This entire snippet is from a book im reading.

# This script prompts to backup files and location
# The files will search on $HOME dir and will only backup files to same $HOME dir.
read -p "Which file types would you like to backup? >>: " file_suffix
read -p "Which directory would you like to backup to? >>: " dir_name
# creates a directory if it does not currently exist
test -d $HOME/$dir_name || mkdir -m 700 $HOME/$dir_name
# search criteria ie .sh . The -path, -prune and -o options are to exclude the back directory from the backup.
find $HOME -path $HOME/$dir_name -prune -o -name "*$file_suffix" -exec cp {} $HOME/$dir_name/ \;
exit 0

3 Answers3

1

The {} has no particular meaning to bash, but does mean something to find.

find . -exec stat {} ";"

Will recursively stat every file reachable from the current working directory with a single invocation of stat per file.

find . -exec stat {} "+"

will run stat with multiple files at once.

You can convince yourself that the {} are really not part of the shell syntax by quoting it or using a variable.

find . -exec stat "{}" ";"

A="{}" find . -exec stat "$A" ";"

will produce the same ouptut as the first example.

Greg Nisbet
  • 3,076
  • 1
    Just for info, + (the plus sign) is not a shell metacharacter so it doesn't need quoting/escaping. See https://unix.stackexchange.com/a/659355/321265 – jaimet May 18 '22 at 13:14
0

If the string {} appears anywhere in the utility name or the arguments it is replaced by the pathname of the current file (found by 'find'). So, in your example, copy {the file that find finds} to $HOME/$dir_name/

kevlinux
  • 389
0

It means the result of the find command, passed as an argument to exec:

Let us say that the result of the find command is x, then:

find ..... -exec echo "{}"

will give output x, because x is passed as an argument and this argument is represented by {}.

In your case, find will give files with the property -path $HOME/$dir_name -prune -o -name "*$file_suffix" and these files will be represented to cp command by {} (one by one not all together).

Prvt_Yadav
  • 5,882