gpt4 book ai didi

Bash - 什么时候在变量前面使用 '$'?

转载 作者:行者123 更新时间:2023-11-29 09:03:44 24 4
gpt4 key购买 nike

我对 bash 脚本编写还很陌生,在网上搜索信息时,我发现了很多看似矛盾的建议。我最困惑的是变量名前面的 $ 。我的主要问题是,什么时候适合、不适合使用该语法?谢谢!

最佳答案

基本上,它在引用变量时使用,但在定义变量时不使用。

当你定义一个变量时,你不使用它:

value=233

调用变量时必须使用它们:

echo "$value"

此基本规则有一些异常(exception)情况。例如在数学表达式中,如 etarion comments .


one more question: if I declare an array my_array and iterate through it with a counter i, would the call to that have to be $my_array[$i]?

看例子:

$ myarray=("one" "two" "three")
$ echo ${myarray[1]} #note that the first index is 0
two

为了遍历它,这段代码使它成为:

for item in "${myarray[@]}"
do
echo $item
done

在我们的例子中:

$ for item in "${myarray[@]}"; do echo $item; done
one
two
three

关于Bash - 什么时候在变量前面使用 '$'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18658190/

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