为什么"申报-f"和"申报-a"在的bash脚本需要的? [英] Why are "declare -f" and "declare -a" needed in bash scripts?

查看:173
本文介绍了为什么"申报-f"和"申报-a"在的bash脚本需要的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,让无辜的问题 - 我只是尝试undertand ...

Sorry for so innocent question - I just try to undertand...

例如 - 我有:

$ 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[@]}

当我运行它,我得到:

And when I run it I get:

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

因此​​,这里是一个问题 - 什么,我必须(如果必须的...)插入声明在这里?
有了它 - 或者没有它它的工作原理一样...

So here is a question - for what i must (if must...) insert declare here? With it - or without it it works the same...

我可以理解,例如声明-i VAR 声明-r VAR 。但是,对于什么是 -f (声明函数)和 -a (声明数组)?

I can understand for example declare -i var or declare -r var. But for what is -f (declare function) and -a (declare array)?

感谢您的提示和链接。

推荐答案

声明-f functionname 用来输出函数的定义 functionname ,如果存在的话,绝对不是的声明的是 functionname 是/将是一个功能。你看:

declare -f functionname is used to output the definition of the function functionname, if it exists, and absolutely not to declare that functionname is/will be a function. Look:

$ 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定义。

So in your case, declare -f testfunct will do nothing, except possibly if testfunct exists, it will output its definition on stdout.

这篇关于为什么"申报-f"和"申报-a"在的bash脚本需要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆