gpt4 book ai didi

shell - shell 脚本中的 ${varname} 和 $varname 有什么区别

转载 作者:行者123 更新时间:2023-12-04 04:51:45 25 4
gpt4 key购买 nike

我有一个简单的问题,但我想知道 ${varname} 和有什么区别和 $varname ?

我两者都使用,但我看不出有什么区别可以告诉我何时使用其中之一。

最佳答案

使用 {} in 变量名有助于在执行变量扩展时消除歧义。

考虑两个变量 varvarname .让我们看看你想附加字符串 name到变量 var .你不能说$varname因为这会导致变量 varname 的扩展.然而,说${var}name会帮助你达到预期的结果。

$ var="This is var variable."
$ varname="This is varname variable."
$ echo $varname
This is varname variable.
$ echo ${var}name
This is var variable.name

访问数组的任何元素时也需要大括号。
$ a=( foo bar baz )       # Declare an array
$ echo $a[0] # Accessing first element -- INCORRECT
foo[0]
$ echo ${a[0]} # Accessing first element -- CORRECT
foo

引自 info bash :

   Any  element  of  an  array may be referenced using ${name[subscript]}.
The braces are required to avoid conflicts with pathname expansion.

关于shell - shell 脚本中的 ${varname} 和 $varname 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19513174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com