简体   繁体   English

[[]]中的Bash ==运算符太聪明了!

[英]Bash == operator in [[ ]] is too smart!

Case in point. 一个很好的例子。 I want to know if some set of files have as a first line '------'. 我想知道一组文件是否作为第一行'------'。

So, 所以,

for file in *.txt
do
    if [[ `head -1 "$file"` == "------" ]]
    then
        echo "$file starts with dashes"
    fi
done

Thing is, head returns the content with a newline, but "------" does not have a newline. 事情是,head使用换行符返回内容,但“------”没有换行符。

Why does it work? 它为什么有效?

The backticks strip the trailing newline. 反引号剥离了尾随换行符。 For example: 例如:

foo=`echo bar`
echo "<$foo>"

prints 版画

<bar>

even though that first echo printed out "bar" followed by a newline. 即使第一个回声打印出“bar”后跟换行符。

Bash performs word splitting on the result of command substitution ie head -1 "$file" Bash对命令替换的结果执行单词拆分,即head -1 "$file"

Word splitting will remove newlines among other things. 单词拆分将删除换行符等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM