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

后端 未结 3 1862
北荒
北荒 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:36

    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.

提交回复
热议问题