Perl: the Markov chain saw | |
PerlMonks |
Escape special chars in a pathby ovedpo15 (Pilgrim) |
on Aug 17, 2022 at 15:30 UTC ( [id://11146197]=perlquestion: print w/replies, xml ) | Need Help?? |
ovedpo15 has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks! My Perl utility generates a bash script that consists of mkdir/rsync/cp commands. This bash script is later used by users (this means that I don't want to actually run those commands when my utility runs, rather just to generate the script). Given a UNIX path, I need to do two different actions - depending on the path type (dir or file): 1. If the path is a directory, then just create it using mkdir. 2. If the path is a file, then just copy the file from the dir directory using rsync or cp (depending if user specified a machine to copy from). For example, consider this: In that case, the bash script will look like: The utility works good, unless a path contains "special chars". I tried to deal with it by escaping and using quotes but I can't seem to cover all cases. By "special chars" I mean chars like ":",";","(",")","_",.... I tried to use the following to subs: I also tried to use quotemeta: But it also failed for a lot of cases and it escaped alot of unneeded chars (like ".", "/", etc. - which are valid in paths without escaping). The code looks like: I of course want to support any kind of path. For example, the special char could contain a "\" before it, and then I need to escape both of them. I built a small test for you to understand what I'm after: If 1 is passed to the script, it will generate directory with one special char (for example: test1/a;b). Then I run the generated bash script and then the test script again - if 0 is passed, it will check if the bash script successfully created dirs & copied files into /tmp. Hope it makes sense. I also noticed that rsync and cp except different escaping. For example, "/test1/a;b/data" works for cp and "/test1/a\;b/data" works for rsync. Is there an easy way to handle special chars in path? All I want is to create mkdir/cp/rsync commands in a bash script that so they will later work. Please help me to fix the wrap_with_quotes and escape subs or find a better way.
Back to
Seekers of Perl Wisdom
|
|