问题描述
通常,我在if语句中使用方括号:
Usually, I use square brackets in the if statement:
if [ "$name" = 'Bob' ]; then ...
但是,当我检查 grep $ c时$ c>成功我不使用方括号:
But, when I check if grep
succeeded I don't use the square brackets:
if grep -q "$text" $file ; then ...
中何时需要方括号如果
声明?
推荐答案
方括号是测试的同义词
命令。 if
语句检查命令的退出状态以决定采用哪个分支。 grep -q$ text
是一个命令,但$ name='Bob'
不是 - 这只是一个表达。 test
是一个命令,它接受一个表达式并对其进行评估:
The square brackets are a synonym for the test
command. An if
statement checks the exit status of a command in order to decide which branch to take. grep -q "$text"
is a command, but "$name" = 'Bob'
is not--it's just an expression. test
is a command, which takes an expression and evaluates it:
if test "$name" = 'Bob'; then ...
因为方括号是测试的同义词
命令,然后您可以将其重写为原始语句:
Since square brackets are a synonym for the test
command, you can then rewrite it as your original statement:
if [ "$name" = 'Bob' ]; then ...
这篇关于何时在Bash if语句中需要方括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!