grep apple file 和 grep "apple" file 有什么区别?

grep apple file 和 grep "apple" file 有什么区别?

grep apple file和之间有什么区别grep "apple" file?加引号有什么作用?它们似乎都起作用,并且执行完全相同的操作(显示同一行)。

答案1

引号会影响 shell 认为哪些字符是特殊的,并具有句法意义。在您的示例中,这没有区别,因为apple不包含这样的字符。

但是请考虑另一个例子:将在文件和中grep apple tree file搜索单词,而将在文件 中搜索单词。引号告诉 bash,单词 space不会开始新的参数,而是应作为当前参数的一部分。会产生相同的结果,因为告诉 bash 忽略以下字符的特殊含义并按字面​​意思处理它。appletreefilegrep "apple tree" fileapple treefile"apple tree"grep apple\ tree file\

答案2

在命令行中使用双引号允许求值,单引号阻止求值,不使用引号允许通配符扩展。以下是人为的例子:

[user@work test]$ ls .
A.txt B.txt C.txt D.cpp

# The following is the same as writing echo 'A.txt B.txt C.txt D.cpp'
[user@work test]$ echo *
A.txt B.txt C.txt D.cpp

[user@work test]$ echo "*"
*

[user@work test]$ echo '*'
*

# The following is the same as writing echo 'A.txt B.txt C.txt'
[user@work test]$ echo *.txt
A.txt B.txt C.txt

[user@work test]$ echo "*.txt"
*.txt

[user@work test]$ echo '*.txt'
*.txt

[user@work test]$ myname=is Fred; echo $myname
bash: Fred: command not found

[user@work test]$ myname=is\ Fred; echo $myname
is Fred

[user@work test]$ myname="is Fred"; echo $myname
is Fred

[user@work test]$ myname='is Fred'; echo $myname
is Fred

理解引号的工作方式对于理解 Bash 至关重要。例如:

# for will operate on each file name separately (like an array), looping 3 times.
[user@work test]$ for f in $(echo *txt); do echo "$f"; done;
A.txt
B.txt
C.txt

# for will see only the string, 'A.txt B.txt C.txt' and loop just once.
[user@work test]$ for f in "$(echo *txt)"; do echo "$f"; done;
A.txt B.txt C.txt

# this just returns the string - it can't be evaluated in single quotes.
[user@work test]$ for f in '$(echo *txt)'; do echo "$f"; done;
$(echo *txt)

您可以使用单引号通过变量传递命令。单引号将阻止求值。双引号将求值。

# This returns three distinct elements, like an array.
[user@work test]$ echo='echo *.txt'; echo $($echo)
A.txt B.txt C.txt

# This returns what looks like three elements, but it is actually a single string.
[user@work test]$ echo='echo *.txt'; echo "$($echo)"
A.txt B.txt C.txt

# This cannot be evaluated, so it returns whatever is between quotes, literally.
[user@work test]$ echo='echo *.txt'; echo '$($echo)'
$($echo)

您可以在双引号内使用单引号,也可以在双引号内使用双引号,但不应在单引号内使用双引号(未对其进行转义)将不会被评估,它们将被按字面解释。不应在单引号内使用单引号(未对其进行转义)。

您需要彻底理解引号才能有效地使用 Bash。非常重要!

作为一般规则,如果我希望 Bash 将某个内容扩展为元素(例如数组),我不会使用引号;对于不会更改的文字字符串,我会使用单引号;对于可能返回任何类型字符串的变量,我会随意使用双引号。这是为了确保空格和特殊字符能够被保留。

相关内容