本文发表在 rolia.net/zh 相约加拿大网上社区枫下论坛
In unix, when you invoke a command under shell, basically the current shell will take your input, and fork() a new process, then exec() your command on top of that process, along with the processed arguments and old shell's enviornment. The shell itself will process the command line according to its own rule, in bash, it will consider "\" as an escape character and take the literal meaning of the character that follows. So,
if you put "\\" in shell, shell will convert it to a single "\" , then pass it to exec() function call. In this case, if you write "echo \\\\\\\\" in shell, the shell will change it to "echo \\\\" (it takes half of the "\" off) and pass this to exec(). When exec() receives its argument of "\\\\", it in turn does its own processing, which also considers "\" as an escape character and thus reduces the "\\\\" to "\\", so, you end up with the output of "\\". Echo has a
peculiar behavior that when it encounters a single "\" who doesn't have anybody else to escape, it will print out "\" anyway. This is why you end up with "\\" too when you input "\\\\\\". This strange escaping behaviour of shell has caused a lot of confusion for reqular expressions, where you need to put double slash before a number in order to represent a previously encoutered RE, such as "\\0"
更多精彩文章及讨论，请光临枫下论坛. 网址: rolia.net/zh