Forward slash vs backward slash for file path in git bash

后端 未结 4 1304
孤街浪徒
孤街浪徒 2021-01-14 08:36

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?

4条回答
  •  爱一瞬间的悲伤
    2021-01-14 09:30

    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.

提交回复
热议问题