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

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

问题描述

我正在为一个 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 是一个命令(也是内置的),正如你所说.这是一个命令,它接受特定类型的参数,并在给定这些参数的情况下以特定方式运行.

[/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.

它接受标志和比较运算符并对它们进行操作以获得 truefalse 结果.然后将该结果转换为返回码.0 表示 true1 表示 false.

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中的if结构

The if construct in the shell is defined

如果列表;然后列出;[ elif 列表;然后列出;] ... [ 其他列表;] fi

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

if 列表被执行.如果其退出状态为零,则执行 then 列表.否则,依次执行每个elif list,如果其退出状态为零,则执行相应的then list,命令完成.否则,执行 else 列表(如果存在).退出状态是最后执行的命令的退出状态,如果没有条件测试为真,则为零.

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.

因此,当 [/test 返回一个退出代码时,该代码就是 if 计算的结果.

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

echo 命令/管道周围不需要(并且不能使用)[ 的原因是因为它不是一组有效的 [ 参数.相反,它是一个命令 list 本身,因此不需要由 [ 评估.您可以直接使用它,并将管道的返回代码交给 if 进行评估.

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