Search code examples
bashfunctiondeclare

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


Sorry for the innocent question - I'm just trying to understand...

For example - I have:

$ 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 - why do I have to (if I have to ...) insert declare here? With it - or without it it works the same...

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


Solution

  • 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.