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

时间:2013-11-02 12:50:02

标签: bash function declare

抱歉这么无辜的问题 - 我只想尝试......

例如 - 我有:

$ 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? 有了它 - 或没有它它的工作原理相同......

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

感谢提示和链接。

3 个答案:

答案 0 :(得分:14)

declare -f functionname用于输出函数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 :)

因此,在您的情况下,declare -f testfunct将不执行任何操作,除非存在testfunct,否则它将在stdout上输出其定义。

答案 1 :(得分:5)

declare -f允许您列出所有已定义的函数(或源代码)及其内容。

使用示例:

[ ~]$ cat test.sh
#!/bin/bash

f(){
    echo "Hello world"
}

# print 0 if is defined (success)
# print 1 if isn't defined (failure)
isDefined(){
    declare -f "$1" >/dev/null && echo 0 || echo 1
}

isDefined f
isDefined g
[ ~]$ ./test.sh 
0
1
[ ~]$ declare -f
existFunction () 
{ 
    declare -f "$1" > /dev/null && echo 0 || echo 1
}
f () 
{ 
    echo "Hello world"
}

然而,巧妙地说下面的gniourf_gniourf:最好使用declare -F来测试函数是否存在。

答案 2 :(得分:5)

据我所知,-a选项本身没有任何实际意义,但我认为在声明数组时可读性是一个优点。当它与其他选项组合以生成特殊类型的数组时,它会变得更有趣。

例如:

# Declare an array of integers
declare -ai int_array

int_array=(1 2 3)

# Setting a string as array value fails
int_array[0]="I am a string"

# Convert array values to lower case (or upper case with -u)
declare -al lowercase_array

lowercase_array[0]="I AM A STRING"
lowercase_array[1]="ANOTHER STRING"

echo "${lowercase_array[0]}"
echo "${lowercase_array[1]}"

# Make a read only array
declare -ar readonly_array=(42 "A String")

# Setting a new value fails
readonly_array[0]=23