加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

为什么这个bash结构有效? (参数取代)

发布时间:2020-12-15 22:11:06 所属栏目:安全 来源:网络整理
导读:码: ${non_existent_variable:whatever}回声“它有效” 结果是有效的.但为什么?部分之前计算为空字符串.试着跑: echo test给出了一个错误. 我偶然尝试为bash创建三元运算符替换,其中set和unset变量的结果不同.它以这种方式工作,但我失去了为什么它的工作
码:
${non_existent_variable:whatever}&&回声“它有效”

结果是有效的.但为什么?部分之前&&计算为空字符串.试着跑:&& echo test给出了一个错误.

我偶然尝试为bash创建三元运算符替换,其中set和unset变量的结果不同.它以这种方式工作,但我失去了为什么它的工作原理.

PARAM = $(${测试_变量:假}&& echo var_exists || echo var_empty)

解决方法

根据 section 2.9.1 of the POSIX spec:

A “simple command” is a sequence of optional variable assignments and redirections,in any sequence,optionally followed by words and redirections,terminated by a control operator.

第2.9.1节的最后一句是相关的:

If there is a command name,execution shall continue as described in Command Search and Execution . If there is no command name,but the command contained a command substitution,the command shall complete with the exit status of the last command substitution performed. Otherwise,the command shall complete with a zero exit status.

因此,如果在所有扩展,重定向等之后,没有找到命令名称,则将其视为成功完成,退出状态为0.

但是,语法不允许在&&和& amp;之前使用空字符串.操作符.以下是语法错误:

&& echo it works

获得完全空的简单命令的唯一方法是在扩展期间使非空字符串“蒸发”.实现这一目标的一种方法是使用不带引号的参数扩展来生成空字符串,这正是${non_existent_variable:whatever}的作用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读