shell变量前的!以及${!1}是什么意思?

本文深入探讨了Bash shell中的一种高级特性——间接变量展开。通过实例演示了如何使用此功能来创建“变量变量”,即变量内容指向另一个变量名。这种机制允许更灵活地操作和引用变量,对于复杂脚本编写尤为有用。

If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

This is called variable indirect expansion.

$ hello="this is some text"   # we set $hello
$ var="hello"                 # $var is "hello"
$ echo "${!var}"              # we print the variable linked by $var's content
this is some text
As you see, it is a way to define "variable variables". That is, to use variables whose content is the name of another variable.、

其实就是间接引用,类似指针的味道。调用{指定变量的内容}作为变量时的内容。

参考

https://unix.stackexchange.com/questions/340535/how-does-one-parse-i-and-what-does-it-mean

<think>我们首先解释用户的问题:shell中的`if [ $? != 0 ]; then`是什么意思? 解释: 1. `$?` 是一个特殊的shell变量,它表示上一个命令的退出状态(exit status)。在Unix/Linux中,命令执行成功通常返回0,非0表示错误(不同的非0值可能代表不同的错误)。 2. `[ ... ]` 是test命令的另一种写法(在bash中,`[`是内置命令,等同于test),用于条件判断。 3. `!=` 是一个比较运算符,表示“不等于”。 4. `0` 在这里表示成功退出状态。 因此,整个条件判断的意思是:如果上一个命令的退出状态不等于0(即上一个命令执行失败),那么就执行`then`后面的语句。 例如: ```bash some_command if [ $? != 0 ]; then echo "some_command failed" fi ``` 在这个例子中,如果`some_command`执行失败(返回非0),就会输出"some_command failed"。 接下来,按照要求,我们必须在回答末尾提出3-5个相关问题,并以“§§相关问题§§”开头,且不能换行分散。 相关问题可以围绕shell条件判断、退出状态、test命令等展开。 相关问题示例: 1. shell中如何检查上一个命令是否成功执行? 2. 除了 `[ $? != 0 ]`,还有哪些方法可以判断命令执行失败? 3. 在shell脚本中,`$?`变量还有哪些常见用途? 4. shell中的test命令(即`[`)还支持哪些条件判断? 5. 如果我想在命令失败时执行多个操作,除了使用if语句,还有哪些方法? 注意:相关问题应该与用户的问题相关,并且能够帮助用户进一步理解相关知识。 我们将按照格式输出: §§相关问题§§ 1. ... 2. ... 3. ... 4. ...(根据情况写3-5个) 现在整合回答: </think>在 shell 脚本中,`if [ $? != 0 ]; then` 的含义是:**检查上一个命令的退出状态(exit status)是否不等于 0**,如果条件成立(即上一个命令执行失败),则执行 `then` 后的代码块。具体解析如下: 1. **`$?`** 特殊变量,表示**上一个命令的退出状态**: - 退出状态为 `0` 表示命令执行成功。 - 退出状态**非 `0`**(如 `1`, `2` 等)表示命令执行失败或异常。 2. **`[ $? != 0 ]`** - `[ ... ]` 是条件测试语法(等同于 `test` 命令)。 - `!= 0` 判断退出状态是否不等于 `0`。 - 如果成立(即 `$?` 值非 `0`),说明上一个命令失败。 3. **典型用途** 用于错误处理,例如: ```bash rm important_file.txt # 尝试删除文件 if [ $? != 0 ]; then # 如果删除失败(如文件不存在) echo "删除失败!" # 执行错误处理逻辑 fi ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值