Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain the inner working of the symbols at the end of this bash: “_ {} \;”

I ran the following command in shell to batch convert .HEIC files to .JPG files, the command is successful, however there's a part of it I don't understand:

find . -name '*.HEIC' -exec sh -c 'magick convert $1 "${1%.HEIC}.JPG"' _ {} \;

Apparently _ {} acts to assign find result to $1, but how? I can't find an explanation on google nor here, and didn't have any luck with man find. It's entirely possible that answers were here but these symbols are not very nice to search for.

So the question is, how does _ {} assign variable to $1? Is it possible to assign multiple variable to it with find/ or other commands?

like image 329
Rocky Li Avatar asked Nov 10 '18 04:11

Rocky Li


1 Answers

There are two things involved in how _ {} assigns the filename to $1. First, is how the find's -exec works: it runs the following arguments (up to the escaped ;) as a command, but with {} replaced with the path to the file it found. Thus, if it finds ./somefile.HEIC, it'll run the equivalent of the command:

sh -c 'magick convert $1 "${1%.HEIC}.JPG"' _ ./somefile.HEIC

The second part is the sh command. sh can do a number of things, but if it's given a -c option, it takes the immediately following argument (magick convert $1 "${1%.HEIC}.JPG") as a command string to parse and run, sort of like a little mini-script. The arguments after that are taken as arguments to that mini-script, starting with $0. In this case, that means it runs the mini-script with $0 set to _, and $1 set to "./somefile.HEIC". If more arguments were supplied, they'd be $2, $3, etc.

like image 91
Gordon Davisson Avatar answered Oct 20 '22 17:10

Gordon Davisson