I have a Perl script that processes a bunch of file names, and uses those file names inside backticks. But the file names contain spaces, apostrophes and other funky characters.
I want to be able to escape them properly (i.e. not using a random regex off the top of my head). Is there a CPAN module that correctly escapes strings for use in bash commands? I know I’ve solved this problem in the past, but I can’t find anything on it this time. There seems to be surprisingly little information on it.
Are you looking for quotemeta?
Update: As hobbs points out in the comments,
quotemetais not intended for this purpose and upon thinking a little more about it, might have problems with embeddednuls. On the other hand String::ShellQuote croaks upon encountering embeddednulls.The safest way is to avoid the shell entirely. Using the list form of ‘system’ can go a long way towards that (I found out to my dismay a few months ago that
cmd.exemight still get involved on Windows), I would recommend that.If you need the output of the command, you are best off (safety-wise) opening a pipe yourself as shown in hobbs’ answer