Remote ssh command escaping

I often have to run non-interactive commands on remote machines (thanks ndenev and famzah). Dealing with quoting and escaping could become quite cumbersome at times. Here’s a very simple example:

for n in "$(cat some\ file.txt |cut -d: -f2)";do echo "$n" |awk '{print $2}' ;done

The thing is, you often debug something on a single server constructing the on-liner iteratively and interactively with no intention to run in on many servers. But then at some point you realize you’d better check on other servers for this problem you’ve been debugging. And you usually find out that your already quite lengthy one-liner must be properly quoted and escaped. One easy way out is to just let CPAN String::ShellQuote do the work for you:

perl -MString::ShellQuote -ne 'chomp; print shell_quote($_),"\n";'

for n in "$(cat some\ file.txt |cut -d: -f2)";do echo "$n" |awk '{print $2}' ;done

'for n in "$(cat some\ file.txt |cut -d: -f2)";do echo "$n" |awk '\''{print $2}'\'' ;done'

This entry was posted in Misc. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *