Arrays BASH:将$1计算为字符串以调用数组长度
我在这里编写了这个函数:我想像这样运行它,Arrays BASH:将$1计算为字符串以调用数组长度,arrays,bash,function,variables,parameters,Arrays,Bash,Function,Variables,Parameters,我在这里编写了这个函数:我想像这样运行它,选择“title” 当它运行时,我希望最终产品与此相同:(用标题替换所有$1) 然而,我得到的只是这个错误: notify.sh: line 67: numChoices=${#$1[@]}: bad substitution 经过相当多的文档整理,我还不能很好地理解替换、指针和引用。有没有人可以帮助你了解一些情况,也许可以纠正我的语法?如果你使用的是bash 4.3,你可以使用nameref变量,如下所示:(我还更新了脚本的各个部分。) 你的选择似乎
选择“title”代码>
当它运行时,我希望最终产品与此相同:(用标题替换所有$1)
然而,我得到的只是这个错误:
notify.sh: line 67: numChoices=${#$1[@]}: bad substitution
经过相当多的文档整理,我还不能很好地理解替换、指针和引用。有没有人可以帮助你了解一些情况,也许可以纠正我的语法?如果你使用的是bash 4.3,你可以使用nameref变量,如下所示:(我还更新了脚本的各个部分。)
你的选择似乎对我有用,谢谢!这就是我需要发生的。@DrewDiezel:酷。但升级时请保留4.3版本。
function choose {
echo title;
randNum=$RANDOM
let "numChoices=${#title[@]}";
let "num=$randNum%$numChoices";
i=0;
while [ $i -lt $numChoices ]; do
if [ $i -eq $num ]; then
echo ${title[$i]};
break;
fi
((i++));
done
}
notify.sh: line 67: numChoices=${#$1[@]}: bad substitution
choose() {
echo $1
# This makes theVar an alias ("nameref") to the variable whose name is in $1
# Like any declare inside a function, it is implicitly local.
declare -n theVar=$1
local randNum=$RANDOM
local numChoices=${#theVar[@]}
local num=$(( randNum % numChoices ))
local i
for (( i=0; i < numChoices; ++i )); do
if (( i == num )); then
echo "${theVar[i]}"
break;
fi
done
}
choose() {
echo $1
local randNum=$RANDOM
# For the indirection, we need to construct the indexed name.
local name=$1[@]
# This hack makes varSize a row of dots with one dot per element.
local varSize=$(printf ".%.0s" "${!name}")
local numChoices=${#varSize}
local num=$(( randNum % numChoices ))
local i
for (( i=0; i < numChoices; ++i )); do
if (( i == num )); then
# Again, we need to construct the complete indexed name.
name=$1[$i]
echo "${!name}";
break;
fi
done
}