1

How to make normal strings (filenames in my case) to Linux CLI/bash escaped strings?

Examples:

"It's a great weather today" -> "It\'s\ a\ great\ weather\ today"

"Wind [Wine]" -> "Wind\ [Wine]"

"/Downloads/RPM's/" -> "/Downloads/RPM\'s/"

I would like to know if there's an easier way to do that, as I am reading filenames in my python script and when I am forwarding them to a bash command, it's failing.

The problem is the number of files are too many and it won't be possible for me to rename or do string manipulation for them.


I am using Python 2.7 on a CentOS 7 System

Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41
  • Are you using `subprocess`? If the `bash` script is written correctly, you shouldn't need to. If the `bash` script *isn't* written correctly, there's no guarantee that doing this will help. – chepner Apr 28 '17 at 11:14
  • `foo="Wind [Wine]"; subprocess.call(["script.bash", foo])`. No escaping of `foo` should be required. – chepner Apr 28 '17 at 11:15

1 Answers1

2

Use shlex, see here, it has arguments for escape, qoutes and escapedqoutes.

  • 1
    Thanks, I also find this link which was also helpful: http://stackoverflow.com/questions/18116465/escape-a-string-for-shell-commands-in-python –  Apr 28 '17 at 09:33