Search code examples
bashunixescapingcygwin

Assign a Variable in bash login shell


i am trying to do this from a Windows command prompt.

 C:\cygwin64\bin\bash --login -c "$var="<hallo>" &&
 echo "$var""

and i get error :

 The system cannot find the file specified.

but this works:

C:\cygwin64\bin\bash --login  -c 
    "var="hello" && echo "$hello""

The login shell seems to cause the problem when it gets a '<'. how can i still assign the string with angle brackets to the shell variable?


Solution

  • When you write

    C:\cygwin64\bin\bash --login -c "$var="<hallo>" && echo "$var""
    

    You are expecting the shell to strip off the outer quotes from that argument to -c and end up with a string that looks like

    $var="<hallo>" && echo "$var"
    

    but that's not what the shell does.

    The shell just matches quotes as it goes along. So the shell sees.

    ["$var="][<hallo>][" && echo "][$var][""].
    

    You need to escape the inner quotes from the current shell or use different quotes to avoid this parsing problem.

    C:\cygwin64\bin\bash --login -c 'var="<hallo>" && echo "$var"'
    

    Note also that I removed the $ from the start of the variable name in the assignment and that I used single quotes on the outside so that the current shell didn't expand $var.

    With double quotes on the outside you'd need to use something like this instead.

    C:\cygwin64\bin\bash --login -c "var='<hallo>' && echo \"\$var\""
    

    For a similar discussion of shell parsing and how things nest (or don't) with backticks you can see my answer here.