Why are “declare -f” and “declare -a” needed in bash scripts?

人走茶凉 提交于 2019-11-30 11:20:39

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 :)

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

As far as I know, the -a option alone does not have any practical relevance, but I think it's a plus for readability when declaring arrays. It becomes more interesting when it is combined with other options to generate arrays of a special type.

For example:

# 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

declare -f allows you to list all defined functions (or sourced) and their contents.

Example of use:

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

However as smartly said gniourf_gniourf below : it's better to use declare -F to test the existence of a function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!