How to make git print paths with back slashes instead of forward slashes in a Windows console

I know it's a little old, but you can use environment variable substitution to replace the / with \ or \\:

C:\> SET FILE=Java/HerpDerp/src
C:\> ECHO %FILE:/=\%
Java\HerpDerp\src

C:\> ECHO %FILE:/=\\%
Java\\HerpDerp\\src

C:\>

To take it a step further, you can write a batch file that does it for a command that outputs a bunch of paths: (git diff --name-only HEAD~1 in the following example)

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "usebackq delims=" %%i IN (`git diff --name-only HEAD~1`) DO (
  SET FILE=%%i
  ECHO !FILE:/=\!
)
ENDLOCAL

git status will be execute through a git bash session, so it would not ever use \ in path (as seen in "Git Bash for Windows showing/expecting file paths with forward-slashes, no drive colon").
See also "Why Windows Uses Backslashes and Everything Else Uses Forward Slashes"

As mentioned, you would have to post-process the output of the command in order to get the correct path format, as in "Bash converting path names for sed so they escape".

st=$(git status)
echo "${st////\\}"

or

echo "${st////\\\\}"

with:
         //  / /  \\\\}"
          ^  ^ ^  ^
          |  | |  |
          |  | |  replacement, backslash needs to be backslashed
          |  | delimiter
          |  string
      global
    substitution

Thank you Lance Clark and VonC. I've been using Git with Windows, Unix/Linux, and Mac for several years, but I never understood how Git works through the Windows Command Shell. I came across this question because I was having trouble with forward slashes in the DOS command shell (the Windows Command Prompt).

In the DOS command shell, I was calling the delete command ("del") to delete a file using the file path returned by "git status", which of course had forward slashes in it. As a result, the error "Invalid switch" was returned or if I wrapped the path in quotes the error was "The system cannot find the path specified." That is when I did a web search and came across this stack overflow question.

The answer led me to learn about Git Bash and how Git really works in Windows. As a result, I'm switching to using Git Bash with Windows whenever possible rather than the DOS command shell. That is also making life easier going back and forth between Windows, Linux, and Mac. My forward slash and backward slash nightmares are mostly better now and I can sleep at night. :)

Here are some links to concise information about Git Bash that helped me understand how it works:

  • Atlassian: Git Bash
  • superuser: What is Git Bash for Windows anyway?

Tags:

Windows

Git