什么时候,如果结构不需要括号? [英] When do if constructs not require brackets?

查看:213
本文介绍了什么时候,如果结构不需要括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一些功课的shell脚本类,并有一个问题问我编写测试进入参数是否是一个有效的shell变量名的脚本。下面的脚本似乎很好地工作。

I'm doing some homework for a shell scripting class and had a question asking me to write a script that tests whether or not the argument entered is a valid shell variable name. The below script seems to work fine.

if echo "$1" | grep -v ".*[^A-Za-z_]" > /dev/null
then
        echo yes
else
        echo no
fi

我明白括号是短手在bash shell测试功能。我的问题是,当我试图用支架上面的脚本我有一个错误。

I understand brackets are short hand for the test function in the BASH shell. My problem is that, when I attempted the above script using brackets I got an error.

if [ echo "$1" | grep -v ".*[^A-Za-z_]" > /dev/null ]

这个问题(我相信)是grep的正试图使用​​]作为它的参数,从而导致当脚本运行错误。

The problem with this (I believe) is that grep is trying to use the ] as its argument, thus resulting in an error when the script is run.

在什么情况下我并不需要括号?

In what situations do I not need brackets?

推荐答案

[ / 测试是一个命令(还内置了),如你所说。这是一个接受对特定类型的参数,并给出这些参数的特定行为方式的命令。

[/test is a command (also a built-in), as you said. It is a command that accepts arguments of a specific sort and behaves in a specific way given those arguments.

它接受标志和比较运营商和经营这些获得真正的结果。然后,它翻译这一结果为返回code。 0 真正 1

It accepts flags and comparison operators and operates on those to obtain a true or false result. It then translates that result into a return code. 0 for true and 1 for false.

如果构造在shell定义

The if construct in the shell is defined

如果列表;然后列出; [ELIF清单;然后列出; ] ... [其他名单; ]网络

if list; then list; [ elif list; then list; ] ... [ else list; ] fi

如果被执行的列表。如果其退出状态为零,则执行然后列表。否则,每个eli​​f的名单依次执行,如果其退出状态为零,则执行相应的话列表和命令完成。否则,执行其他列表中,如果present。退出状态是最后执行的命令的退出状态,或者零,如果所有条件都不满足。

The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true.

所以,当 [ / 测试返回退出code这就是如果评估。

So when [/test returns an exit code that is what if evaluates.

您不需要(且不能使用)的原因 [围绕回声命令/管道是因为这不是 [参数的有效集。相反,这是一个命令列表本身,因此,并不需要由评估[。你可以简单地直接使用它,并有管道,如果交给的评价;返回code。

The reason you don't need (and can't use) [ around the echo command/pipeline is because that isn't a valid set of [ arguments. Instead that is a command list itself and, as such, does not need to be evaluated by [. You can simply use it directly and have the return code of the pipeline handed to if for evalution.

这篇关于什么时候,如果结构不需要括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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