在阅读了 ilkkachu 对这个问题的回答后,我了解到内置的declare
(带参数-n
)shell的存在。
help declare
带来:
设置变量值和属性。
声明变量并赋予它们属性。如果没有给出名称,则显示所有变量的属性和值。
-n ... 使 NAME 成为对其值命名的变量的引用
我要求用一个例子declare
做一个一般性的解释,因为我不理解man
. 我知道什么是变量和扩大,但我还是错过了man
上declare
(可变属性?)。
也许您想根据 ilkkachu 在答案中的代码来解释这一点:
#!/bin/bash
function read_and_verify {
read -p "Please enter value for '$1': " tmp1
read -p "Please repeat the value to verify: " tmp2
if [ "$tmp1" != "$tmp2" ]; then
echo "Values unmatched. Please try again."; return 2
else
declare -n ref="$1"
ref=$tmp1
fi
}
Run Code Online (Sandbox Code Playgroud) 做 declare -a A
创建一个空的数组A
在bash,或者它只是设置的情况下,一个属性A
被分配到以后呢?
考虑这个代码:
set -u
declare -a A
echo ${#A[*]}
echo ${A[*]}
A=()
echo ${#A[*]}
echo ${A[*]}
A=(1 2)
echo ${#A[*]}
echo ${A[*]}
Run Code Online (Sandbox Code Playgroud)
预期的输出应该是什么?
在 Bash 4.3.48(1) 中,我bash: A: unbound variable
在查询declare
. 访问所有元素时,我也会收到该错误。我知道更高版本的 Bash 对此有不同的处理方式。我仍然想知道是否declare
实际定义了一个变量(为空)。
我偶然发现了以下bash
行为,这对我来说有点出乎意料。
# The following works
$ declare bar=Hello # Line 1
$ declare -p bar # Line 2
declare -- bar="Hello"
$ foo=bar # Line 3
$ declare ${foo}=Bye # Line 4
$ declare -p bar # Line 5
declare -- bar="Bye"
# The following fails, though
$ declare -a array=( A B C ) # Line 6
$ declare -p array # Line 7
declare -a array=([0]="A" [1]="B" [2]="C")
$ foo=array # Line 8
$ declare -a …
Run Code Online (Sandbox Code Playgroud) 这是专门关于bash
的- 在这个答案declare
中对一般情况进行了非常详尽的处理(其中提到“ // , ,的输出”,但没有提到的输出)。typeset
declare
export -p
ksh93
mksh
zsh
bash
给定一个本地/导出/数组/关联数组(但可能不是 nameref)变量, infoo
的输出是否保证可重用?官方文档没有提到类似的内容:declare -p foo
bash
bash
该
-p
选项将显示每个的属性和值name
。当-p
与参数一起使用时,除和name
之外的其他选项将被忽略。-f
-F
我浏览了一下CHANGES
,看到了关于函数的内容:
This document details the changes between this version, bash-2.05-beta1,
and the previous version, bash-2.05-alpha1.
...
b. When `set' is called without options, it prints function definitions in a
way that allows …
Run Code Online (Sandbox Code Playgroud) 我的目标是理解“变量属性”的一般概念,希望它能帮助我理解Bash 中的声明。
什么是可变属性?为什么有人要为变量赋予属性?为什么在使用变量时不只是创建一个变量并在执行中扩展它们就“足够了”?