当方括号需要在bash if语句? [英] When square brackets are required in bash if statement?

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

问题描述

通常情况下,我用方括号中的if语句:

Usually, I use square brackets in the if statement:

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

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

if grep -q "$text" $file ; then ...

在方括号是在如果语句有必要吗?

When the square brackets are necessary in the if statement?

推荐答案

的方括号是用于测试命令的代名词。一个如果语句检查,以决定采取哪一个分支指令的退出状态。 的grep -q$文字是一个命令,但$名='鲍勃'是不是 - 它只是一个前pression。 测试是一个命令,这需要一个前pression并评估它:

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天全站免登陆