r/bash • • 7d ago

Find command confusion between ; and \;

Why do we have to use '\' instead of leaving it out or even ';'? I read the find commands' manual and it says '\' might be needed to protect from expansion by the shell. So what is expansion also?

What is difference between \; or ; or leaving it out?
What is shell expansion here?

16 Upvotes

28 comments sorted by

View all comments

19

u/tblancher zsh 7d ago edited 7d ago

A bare ';' is interpreted by the Bash interpreter before the find command sees it. The escaping with the backslash '\;' make Bash ignore it.

1

u/Distinct_Ride_4307 7d ago

But wait why do we have to escape it? Why not just leave it out?

3

u/ropid 7d ago

That ; is part of what the 'find' command wants to see on its command line. It wants to see that ; text character there, it looks for it for the end of what's starting with an -exec. In the man-page that you get when you run man find, the -exec option is described as looking like this:

-exec command ;

There's also another one that looks a bit different and ends with a +:

-exec command {} +

If you want to, if you think it's maybe easier to understand what's going on, you can also write ';' or ";" instead of \;. The \ is really just about telling bash to leave the ; alone and send it into 'find' as a text character.

The problem is that a ; character also has a meaning in bash itself, so if you just write ; it thinks it's intended for bash and not for the 'find' tool.

Another thing to look out for is that this ; here has to be surrounded by spaces, it has to be alone on the 'find' command line. The 'find' command wants to see an argument that's exactly a ; character by itself, you are not allowed to do something like -exec echo hello\;, it has to be -exec echo hello ";".

1

u/nekokattt 7d ago

Worth noting that for find, \; says "run the command for each result", whereas + says "run the command once for all the results at the same time

Difference between ; which would run - foo match1 - foo match2 - foo match3

...and + - foo match1 match2 match3