Yvon
Yvon

Reputation: 2993

WSL - White space breaks bash command in CMD batch script

In test.cmd -

wsl echo "Incoming File - $(printf %%q "$(wslpath -ua "%~dpnx1")")"
wsl ls -la "$(printf %%q "$(wslpath -ua "%~dpnx1")")"
pause

In C:\test, I have two files nospace.txt and has space.txt

When I drag nospace.txt to test.cmd -

C:\test>wsl echo "Incoming File - $(printf %q "$(wslpath -ua "C:\test\nospace.txt")")"
Incoming File - /mnt/c/test/nospace.txt

C:\test>wsl ls -la "$(printf %q "$(wslpath -ua "C:\test\nospace.txt")")"
-rwxrwxrwx 1 yvon yvon 0 Feb  2 18:09 /mnt/c/test/nospace.txt

C:\test>pause
Press any key to continue . . .

When I drag has space.txt to test.cmd -

C:\test>wsl echo "Incoming File - $(printf %q "$(wslpath -ua "C:\test\has space.txt")")"
Incoming File - /mnt/c/test/has\ space.txt

C:\test>wsl ls -la "$(printf %q "$(wslpath -ua "C:\test\has space.txt")")"
ls: cannot access '/mnt/c/test/has\ space.txt': No such file or directory

C:\test>pause
Press any key to continue . . .

It seems WSL does not appreciate escapes for white spaces. Why?

Upvotes: 1

Views: 1061

Answers (2)

Compo
Compo

Reputation: 38642

By all means you can use printf with %q to see the escaped version of your input file argument:

wsl printf '%%s' "Incoming File - $(printf '%%q' "$(wslpath -ua "%~f1")")"

However, unless you're copying and pasting it somewhere, I'm not sure why you'd need to do that, so the following should be sufficient:

wsl printf '%%s' "Incoming File - $(wslpath -ua "%~f1")"

Your second command, shouldn't have any issues with the space characters, so there's no need to use printf or %q, the following should suffice:

wsl ls -la "$(wslpath -ua "%~f1")"



If neither of these example lines are your intention, you should consider revising your question, to make it clear what you intended to ask.

Upvotes: 0

Yvon
Yvon

Reputation: 2993

Don't use printf. Don't escape the file name at all.

wsl echo "Incoming File - $(wslpath -ua "%~dpnx1")"
wsl ls -la "$(wslpath -ua "%~dpnx1")"

Output -

C:\test>wsl echo "Incoming File - $(wslpath -ua "C:\test\has space.txt")"
Incoming File - /mnt/c/test/has space.txt

C:\test>wsl ls -la "$(wslpath -ua "C:\test\has space.txt")"
-rwxrwxrwx 1 yvon yvon 0 Feb  2 18:09 '/mnt/c/test/has space.txt'

Upvotes: 1

Related Questions