Sabin Antohe
Sabin Antohe

Reputation: 41

was unexpected at this time

I am trying to write a script that prints a variable. This is the code:

@echo off

set workspace=%CD%
set artifact_ids=online_deploy

for %%x in (%artifact_ids%) do (
    echo %workspace%
)

I get this error when I run the script from any folder inside C:\Program Files (x86): \ was unexpected at this time.

I am guessing there is a problem with the path name since I can run it succesfully from anywhere else except for Program Files (x86).

Any help will be appreciated.

Upvotes: 0

Views: 4129

Answers (3)

Stephan
Stephan

Reputation: 56180

The problem is, that the variable is expanded "too early", so the ) from Program Files (x86) accidently closes the for loop.

There are at least three methods to safely handle this issue (besides using shortnames):

1) enclosing the string in quotes: echo "%workspace%", set "var=%workspace%"
2) escaping the closing paranthese
3) Delayed expansion

The following example shows all three methods:

@echo off
setlocal enabledelayedexpansion
set "workspace=%ProgramFiles(x86)%"
set "artifact_ids=online_deploy"
for %%x in (%artifact_ids%) do (
    echo using quotes: "%workspace%"
    echo escaping:     %workspace:)=^)%
    echo delayed exp.: !workspace!
)

What method is the best, depends on your acutal code. There are pros and cons with all of them.

Upvotes: 2

lit
lit

Reputation: 16236

Use the short name for the "Program Files (x86)" directory. Actually, it works on all directories. There might be other directories that contain spaces and special characters.

set "workspace=%CD%"
FOR /F "tokens=*" %%p IN ("%workspace%") DO (SET "workspace=%%~sp")

Upvotes: 2

Magoo
Magoo

Reputation: 80023

Sadly, your code as posted does not demonstrate the problem. You're apparently substituting echo for the actual command you're using. Commendable, but in this case, misleading.

The problem is that the ) is being interpreted as the closing parenthesis of the do. How to fix it will depend on your actual code.

Upvotes: 0

Related Questions