为什么在bash脚本中需要“declare -f”和“declare -a”?

对不起,如此无辜的问题 – 我只是试图承诺…

例如 – 我有

$cat test.sh
#!/bin/bash
declare -f testfunct

testfunct () {
echo "I'm function"
}

testfunct

declare -a testarr

testarr=([1]=arr1 [2]=arr2 [3]=arr3)

echo ${testarr[@]}

当我运行它,我得到:

$./test.sh
I'm function
arr1 arr2 arr3

所以这里是一个问题 – 我必须(如果必须…)在这里插入声明?
有了它 – 或没有它它的工作原理相同…

我可以理解,例如declare -i var或declare -r var.但是什么是-f(声明函数)和-a(声明数组)?

感谢提示链接.

declare -f functionname用于输出函数functionname的定义,如果它存在,绝对不要声明该函数名是/将是一个函数.看:
$unset -f a # unsetting the function a,if it existed
$declare -f a
$# nothing output and look at the exit code:
$echo $?
1
$# that was an "error" because the function didn't exist
$a() { echo 'Hello,world!'; }
$declare -f a
a () 
{ 
    echo 'Hello,world!'
}
$# ok? and look at the exit code:
$echo $?
0
$# cool :)

所以在你的情况下,声明-f testfunct不会做任何事情,除了可能如果testfunct存在,它将输出它在stdout上的定义.

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...