Search code examples
bashbackslashappcmd

Appcmd from Bash script replacing backslashes with forward slashes, how to prevent?


I'm trying to run a Bash script which calls appcmd to add a site to IIS.

#!/bin/bash

windir=c:\\windows
domain="$1"
path="$2"

#also tried using forward slashes by replacing backslashes
#physicalPath=`echo "$path" | sed 's/\\\\/\//g'`

#add site
$windir\\syswow64\\inetsrv\\appcmd add site /name:$domain /physicalpath:$path

I'm calling the script using:

script.sh mydomain.com c:\mypath

However when I check IIS, the Physical Path property of the site is set using forward slashes instead of backslashes.

appcmd Bash

What am I doing wrong?


Solution

  • Backslashes are used to prevent special treatment of certain characters:

    $ z=foo
    $ echo "$z"
    foo
    $ echo "\$z"
    $z
    

    Because of this, you need escape backslashes themselves in order to use them literally. Each pair \\ is seen by the shell as a single literal \.

    windir=c:\\\\windows
    domain="$1"
    path="$2"
    
    #add site
    "$windir"\\\\syswow64\\\\inetsrv\\\\appcmd add site /name:"$domain" /physicalpath:"$path"
    

    However, a simpler way to escape them is to include them in single quotes.

    windir='c:\\windows'
    domain="$1"
    path="$2"
    
    #add site
    "$windir"'\\syswow64\\inetsrv\\appcmd' add site /name:"$domain" /physicalpath:"$path"
    

    (You can use double quotes as well, but since there are a few characters that have special meaning in double quotes, a backslash can be used to escape them, which means sometimes you need to escape a backslash, sometimes you don't. For example:

    $ echo "\$"
    $
    $ echo "\t"
    \t
    

    )