J33nn J33nn - 2 years ago 98
Bash Question

Perl escaping argument for bash execution

I've written some code in Perl which executes some bash command within its execution. My problem was when bash command attributes contained white space inside which failed bash command execution. But I've managed to work with those argument simply adding quotes around argument. Unfortunately during tests I've found that my script fails when

character is placed at the end of variable which obviously escapes bash execution quotes and fails bash command. For example:

my $arg1 = 'This is sample text which can be put into variable. And a random sign\\';
`echo "$arg1"`

Is there any chance to automatically escape special characters in variable?

Answer Source

It's much easier to use single quotes in bash; then the only character you need to worry about is a single quote itself.

($arbitrary_string) =~ s/'/'"'"'/g;

`echo '$arbitrary_string'`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download