Shell – How to escape spaces etc in passed variable, for system call to cp in awk

awkquotingshell-script

This problem has enough layers of complexity to make simple escaping characters difficult for me. I have a bash script which, for a large part, has an embedded awk script that reads a file delimited by semicolons. In this text file, one of the fields is a directory path to some JPEGs. I'd like to copy the JPEGs somewhere else, but the original directory path has spaces in it (and could potentially have other strings that could do damage). I can't refer to the directory in question with single quotes because this stops the awk interpreter, and double quotes turns it into a literal string in awk.

I'm using gawk 4.1.1. Here's some awk code of what I'm trying to accomplish:

imageDirectory = $1;
cpJpegVariable="cp -r " imageDirectory " assets";
#screws up if imageDirectory has spaces and other naughty characters
system(cpJpegVariable);

Best Answer

You can use:

awk '...
    cpJpegVariable="cp -r '\''" imageDirectory "'\'' assets";
    ...'

(note that ' doesn't need escaping for awk, but you need '\'' for the shell). So when awk expands variable cpJpegVariable, it looks like:

cp -r 'file_contain space' assets

With that, you can avoid problem with all special characters, except ' itself. If imageDirectory may contain single quote characters, you can escape them with gsub(). Example:

awk '{gsub("'\''","'\''\"'\''\"",imageDirectory)}1'
Related Question