shell脚本双引号
我正在编写一个解析日志文件的 shell 脚本。重要的部分是这样的:
rx=$(echo "$logfile" | grep -o "rx_value.*" | grep -o "[0-9]\{1,10\}")
echo rx=$rx
以下内容打印到 STDOUT (错误):
rx=
如果我像这样从 $logfile 中删除双 qoutes:
rx=$(echo $logfile | grep -o "rx_value.*" | grep -o "[0-9]\{1,10\}")
echo rx=$rx
以下内容打印到 STDOUT (正确):
rx=0
我很确定这是一个很好用的东西变量周围有双引号,因此我在脚本中的所有变量上都使用了它们。到目前为止我找到的信息表明,如果不将变量放在双引号中,结果可能会因为分词、通配符等而变得错误。
任何人都可以解释这里发生了什么吗?
编辑:
$logfile 包含使用 wget 下载的日志文件:
$logfile=(wget -q -O -"http://www.example.com")
I am writing a shell script that parses a logfile. The important part is this:
rx=$(echo "$logfile" | grep -o "rx_value.*" | grep -o "[0-9]\{1,10\}")
echo rx=$rx
The following is printed to STDOUT (WRONG):
rx=
If i remove the double qoutes from $logfile like this:
rx=$(echo $logfile | grep -o "rx_value.*" | grep -o "[0-9]\{1,10\}")
echo rx=$rx
The following is printed to STDOUT (CORRECT):
rx=0
I was pretty sure that it was a good thing to use double quotes around variables, so I have used them on all variables in my script. The information I have found so far, says that if one do NOT put double quotes around variables, the result could become wrong because of word splitting, globbing etc.
Can anyone explain what is happening here?
Edit:
$logfile contains the logfile downloaded with wget:
$logfile=(wget -q -O -"http://www.example.com")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您的日志文件在 rx_value 和您要查找的数字之间有一个换行符。带有不带引号的参数扩展的 echo 命令会将换行符转换为空格。请参阅文档中的单词拆分或字段拆分。
I think your
logfile
has a newline betweenrx_value
and the number you are looking for. Theecho
command with an unquoted parameter expansion will convert the newline to a space. See word splitting or field splitting in the documentation.如果在输出中引用变量会发生什么?
不这样做通常是“神秘”行为的根源。
What happens if you quote the variable on output?
Not doing this is often the source of "mysterious" behavior.
您没有提到
$logfile
的值。您的信息是正确的 - 无引号和双引号之间的区别正是字段拆分和通配符。因此,如果您依赖其中之一来发生,您将得到带有双引号的错误结果。更新。好的,您的变量包含使用
wget
检索的日志文件。我可以建议使用管道代替吗?但这可能会输出与您的双引号示例相同的输出,并且我会比您认为的正确答案更相信这一点。
You didn't mention the value of
$logfile
. Your information is correct -- the difference between no quotes and double quotes is precisely field splitting and globbing. So if you rely on one of them to happen, you will get wrong results with double quotes.UPDATE. Okay, so your variable containt a log file retrieved with
wget
. May I suggest using a pipe instead?But this will probably output the same that your double-quoted example, and I would trust this more than what you think is correct answer.