简体   繁体   中英

Execute commands with spaces in shell script

I have this script:

build.sh

#!/bin/bash
MSBUILD="/c/Program\ Files \(x86\)/MSBuild/14.0/Bin/msbuild.exe my.sln //p:Configuration=Debug //t:Rebuild"
$MSBUILD

Error

/c/Program: No such file or directory

I've tried many combinations of the above. Bash will not recognize that space in the path. How can I execute this?

Someone with more insight in bash should be able to explain the exact mechanism behind this because I can't, but I do know how to apply a solution : only use quotes when expanding the variable (else the quotes are also interpreted apparently) and use an array else you cannot not use quotes.. Also note that / should be single.

MSBUILD[0]=/c/Program\ Files \(x86\)/MSBuild/14.0/Bin/msbuild.exe
MSBUILD[1]=my.sln
MSBUILD[2]=/p:Configuration=Debug

"$MSBUILD[@]"

This is what I ultimately used:

MSBUILD[0]="/c/Program Files (x86)/MSBuild/14.0/Bin/msbuild.exe"
MSBUILD[1]=./mySolutionName.sln
MSBUILD[2]=/property:Configuration=Debug
MSBUILD[3]=/target:Clean,Build

"${MSBUILD[0]}" "${MSBUILD[1]}" "${MSBUILD[2]}" "${MSBUILD[3]}"

I stumbled across a similar issue dealing with variable expansion . Also note that the shorthands did not work for me:

"/p:Configuration=Debug" becomes "/property:Configuration=Debug"

When you work with paths/commands that contains spaces, you need to quote the path first, this will work for you:

test.proj

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <Target Name="Build">
    <Message Text="Hello World! $(ABC)" Importance="high"/>
  </Target>

</Project>

build.sh

#!/bin/bash
MSBUILDPATH=c:/Program\ Files\ \(x86\)/MSBuild/14.0/Bin/msbuild.exe
"$MSBUILDPATH" test.proj //t:build //p:ABC=123

or (With backslashes insted)

#!/bin/bash
MSBUILD=c\:\\Program\ Files\ \(x86\)\\MSBuild\\14.0\\Bin\\msbuild.exe
"$MSBUILD" test.proj //t:build //p:ABC=123

I'm passing the target (/t:) and property (/p:) without problems just use double slashes for them. Also note the colon (:) after the drive letter.

If you need to pass a property that contains spaces just do this:

"$MSBUILD" test.proj //t:build //p:ABC="123 456 789"

You can define your paths first and then use them in quotes to execute the command.

You can copy paste this exaple and it will work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM