假设在 中创建了一个动态命名的变量zsh
,因此:
name="hello"
typeset $name=42
echo ${(P)${name}} # Prints the variable $hello, which is 42
Run Code Online (Sandbox Code Playgroud)
现在,假设一个人想要增加或更改所述变量,但不知道它的直接名称,即我希望类似于以下内容的工作:
(( ${(P)${name}} = ${(P)${name}} + 1 )) # Set $hello to 43?
Run Code Online (Sandbox Code Playgroud)
以上不起作用 - 什么会?
$\xc2\xa0name=hello\n$\xc2\xa0hello=42\n$\xc2\xa0(($name++))\n$\xc2\xa0echo $hello\n43\n
Run Code Online (Sandbox Code Playgroud)\n\n就像任何类似 Korn 的 shell 一样。或者 POSIXly:
\n\n$ name=hello\n$ hello=42\n$ : "$(($name += 1))"\n$ echo "$hello"\n43\n
Run Code Online (Sandbox Code Playgroud)\n\n要点是,所有参数扩展、命令替换和算术扩展都是在计算算术表达式之前在算术表达式内完成的。
\n\n((something))\n
Run Code Online (Sandbox Code Playgroud)\n\n类似于
\n\nlet "something"\n
Run Code Online (Sandbox Code Playgroud)\n\n因此,在(($name++))
(如let "$name++"
)中, that 首先扩展为hello++
,并将其计算为++
应用于hello
变量的运算符。
POSIXsh
没有((...))
运算符,但有$((...))
算术扩展运算符。它没有++
(尽管它允许实现将其作为扩展,而不是要求它是一元和/或二元+
运算符的组合),但它有+=
。
通过使用: "$((...))"
where :
is null 命令,我们得到类似于 ksh\'s 的内容((...))
。尽管严格等价的是[ "$((...))" -ne 0 ]
,但当((expression))
表达式解析为 0 时,as 返回 false。
归档时间: |
|
查看次数: |
4145 次 |
最近记录: |