Stack Johan
Stack Johan

Reputation: 379

Why am I getting three outputs when I have a space in batch variable?

The code is intended to be a simple symbolic link creator for the test.tx file, but when I run it I get three outputs:

mklink "H:\Backups\Batch Files\Batch" "H:\Backups\Batch Files\File System\test.txt"
mklink "H:\Backups\Batch Files\File" "H:\Backups\Batch Files\File System\test.txt"
mklink "H:\Backups\Batch Files\test.txt" "H:\Backups\Batch Files\File System\test.txt"

Script:

@Echo off

set "src=H:\Backups\Batch Files\File System\test.txt"
set "des=H:\Backups\Batch Files"

FOR %%A IN (%src%) DO (echo mklink "%des%\%%~nxA" "%src%")

timeout 30

Upvotes: 0

Views: 15

Answers (1)

Magoo
Magoo

Reputation: 80193

the value assign to src is H:\Backups\Batch Files\File System\test.txt.

This is three separate space-separated strings, hence for will do the echo three times, once with each string.

If you want cmd to interpret the string as a single entity, you can

1/ Quote the string when assigned, set "src="H:\Backups\Batch Files\File System\test.txt""
or
2/ Quote the value when used FOR %%A IN ("%src%") DO (...

Upvotes: 2

Related Questions