bash 为什么通过 echo 运行时反斜杠会消失?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10238617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do backslashes disappear when run through echo?
提问by Village
I have code like this, which processes a CSV file:
我有这样的代码,它处理一个 CSV 文件:
#!/bin/bash
while read line
do
variable=$(echo $line | awk -F, '{print }')
echo $variable
done < ./file.csv
If the CSV file contains any \, when I run this command, the output text does not show the \.
如果 CSV 文件包含任何\,当我运行此命令时,输出文本不会显示\.
How can I ensure that \is not deleted?
我怎样才能确保\不被删除?
回答by Zash
The reason for this behaviour is that the readbuiltin uses \as escape character. The -rflag disables this behaviour.
这种行为的原因是read内置函数\用作转义字符。该-r标志禁用此行为。
So, this should work:
所以,这应该有效:
while read -r line
variable=$(echo $line | awk -F, '{print }')
echo $variable
done < ./file.csv
You should also place "..."around things like $(...)and variables, like
您还应该放置"..."诸如$(...)和变量之类的东西,例如
variable="$(command)"
echo "$variable"
回答by Norman Ramsey
The man page for bashhas this to say about read:
的手册页bash有这样的说法read:
The backslash character (\) may be used to remove any special meaning for the next character read and for line continuation.
反斜杠字符 (\) 可用于删除下一个读取字符和行继续的任何特殊含义。

