Forward slash vs backward slash for file path in g

2019-06-03 19:12发布

问题:

I am running these two commands in Git bash.

Why they behave differently? Aren't they supposed to do the same thing or am I missing something?

git diff > D:\Patches\afterWGComment.txt  

creates file PatchesafterWGComment.txt in D:/

git diff > D:/Patches/afterWGComment.txt  

correctly creates file afterWGComment.txt in D:/Patches/

Note that D:/Patches/ folder is present before running the above commands.

回答1:

Bash treats backslash as an escape character, meaning that the symbol following it is interpreted literally, and the backslash itself is dropped.

$ echo $HOME
/home/user
$ echo \$HOME
$HOME

Under Windows, where backslash serves as a path separator, this causes some inconvenience. Fortunately, inside single quotes a backslash character loses its special meaning and is treated literally (as any other character, except a single quote):

$ echo '\$HOME'
\$HOME

Therefore, if you are going to copy&paste a Windows path into Git bash, put it inside single quotes:

git diff > 'D:\Patches\afterWGComment.txt'


回答2:

Backslash is an escape character used to escape meta characters. This means you need to escape the escape:

D:\\Patches\\afterWGComment.txt

Alternative you can put your string in single quotes, which will make all characters literal:

'D\Patches\afterWGComment.txt'

Some meta characters: *, ~, $, !, ...



回答3:

Well the Backslash (\) in Linux generally means a escape character. So in your case the backslash is escaping strings. Try with a cd "D:\Patches\afterWGComment.txt" and you can see the difference.



回答4:

The back slash has a very long history in Unix (and therefore in Linux) of meanning: quote next character.

There are three ways to quote in the shell (where you type commands):

  • The backquote (\)
  • Single quotes (')
  • Double quotes (")

In the order from stronger to softer. For example, a $ is an special character in the shell, this will print the value of a variable:

$ a=Hello
$ echo $a
Hello

But this will not:

$ echo \$a
$a

$ echo '$a'
$a

$ echo "$a"
Hello

In most cases, a backslash will make the next character "not special", and usually will convert to the same character:

$ echo \a
a

Windows decided to use \ to mean as the same as the character / means in Unix file paths.
To write a path in any Unix like shell with backslashes, you need to quote them:

$ echo \\
\
$ echo '\'
\
$ echo "\\"
\

For the example you present, just quote the path:

$ echo "Hello" > D:\\Patches\\afterWGComment.txt

That will create the file afterWGComment.txt that contains the word Hello.

Or:

$ echo "Hello" > 'D:\Patches\afterWGComment.txt'
$ echo "Hello" > "D:\\Patches\\afterWGComment.txt"
$ echo "Hello" > "D:/Patches/afterWGComment.txt"

Quoting is not simple, it has adquired a long list of details since the 1660's.