Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to escape a variable in bash when passing to command line argument
    text
    copied!<p>I've got a bash script (cygwin) that uses some windows paths with spaces in them. Consequently, I have escaped the space with a \ in my variable definition. Everything within the script works fine. However, I need to pass this variable as an argument to command line executable. When I do that, my escaping gets messed up.</p> <p>Sample non-functional script:</p> <pre><code>#!/bin/sh # file paths destinationPath="/cygdrive/c/Documents and Settings/Eric/My Documents/" attachments="\n2013-12-12.pdf" body="Test Body" recipient="asdf@asdf.com" # prepare attachments args="" for file in $attachments ; do file=${file//[ \\n]/} touch $file mv $file "$destinationPath/$file" args="$args -a $destinationPath/$file" done # send email echo -e $body | email --from-addr nosender@mydomain.com --from-name "Automated CSS Downloader" --subject "Downloaded new file(s) \ from CSS" $args eric@mydomain.com </code></pre> <p>Output from the script:</p> <pre><code>$ bash -x test.sh + destinationPath='/cygdrive/c/Documents and Settings/Eric/My Documents/' + attachments='\n2013-12-12.pdf' + body='Test Body' + recipient=asdf@asdf.com + args= + for file in '$attachments' + file=2013-12-12.pdf + touch 2013-12-12.pdf + mv 2013-12-12.pdf '/cygdrive/c/Documents and Settings/Eric/My Documents//2013-12-12.pdf' mv: listing attributes of `2013-12-12.pdf': Invalid argument + args=' -a /cygdrive/c/Documents and Settings/Eric/My Documents//2013-12-12.pdf' + echo -e Test Body + email --from-addr nosender@mydomain.com --from-name 'Automated CSS Downloader' --subject 'Downloaded new file(s) from CSS' -a /cygdrive/c/Documents and Settings/Eric/My Documents//2013-12-12.pdf eric@mydomain.com email: WARNING: Email address 'and' is invalid. Skipping... email: FATAL: Could not open attachment: /cygdrive/c/Documents: No such file or directory </code></pre> <p>So, as you can see the escaped space in the path is not being exported in the $args variable. I am assuming the error comes on the line "args=...". But I am not sure how to escaped $destinationPath to ensure that the escaped characters are retained.</p> <p>I've tried using double quotes (with no escaped space) in destinationPath but to no avail. If I try to double quote $destinationPath in the args= line, then the output also gets all screwed up with a bunch of extra quoting.</p> <p>How can I get this to work? I've tried playing around with the $IFS variable, but I don't really know what I'm doing with it, and can't seem to get it working with that either, although I suspect the solution has something to do with $IFS.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload