何时在Bash if语句中需要方括号? [英] When are square brackets required in a Bash if statement?

查看:229
本文介绍了何时在Bash if语句中需要方括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我在if语句中使用方括号:

Usually, I use square brackets in the if statement:

if [ "$name" = 'Bob' ]; then ...

但是,当我检查 grep 成功我不使用方括号:

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语句中需要方括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆