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

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

    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
    

提交回复
热议问题