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

后端 未结 3 1878
北荒
北荒 2020-12-31 03:00

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

For example - I have:

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

testfunct ()          


        
3条回答
  •  执念已碎
    2020-12-31 03:32

    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.

提交回复
热议问题