How to return an array in bash without using globals?

后端 未结 18 2046
Happy的楠姐
Happy的楠姐 2020-11-29 21:36

I have a function that creates an array and I want to return the array to the caller:

create_array() {
  local my_list=(\"a\", \"b\", \"c\")
  echo \"${my_li         


        
18条回答
  •  感情败类
    2020-11-29 21:54

    If your source data is formatted with each list element on a separate line, then the mapfile builtin is a simple and elegant way to read a list into an array:

    $ list=$(ls -1 /usr/local)           # one item per line
    
    $ mapfile -t arrayVar <<<"$list"     # -t trims trailing newlines
    
    $ declare -p arrayVar | sed 's#\[#\n[#g'
    declare -a arrayVar='(
    [0]="bin"
    [1]="etc"
    [2]="games"
    [3]="include"
    [4]="lib"
    [5]="man"
    [6]="sbin"
    [7]="share"
    [8]="src")'
    

    Note that, as with the read builtin, you would not ordinarily* use mapfile in a pipeline (or subshell) because the assigned array variable would be unavailable to subsequent statements (* unless bash job control is disabled and shopt -s lastpipe is set).

    $ help mapfile
    mapfile: mapfile [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
        Read lines from the standard input into an indexed array variable.
    
        Read lines from the standard input into the indexed array variable ARRAY, or
        from file descriptor FD if the -u option is supplied.  The variable MAPFILE
        is the default ARRAY.
    
        Options:
          -n count  Copy at most COUNT lines.  If COUNT is 0, all lines are copied.
          -O origin Begin assigning to ARRAY at index ORIGIN.  The default index is 0.
          -s count  Discard the first COUNT lines read.
          -t                Remove a trailing newline from each line read.
          -u fd             Read lines from file descriptor FD instead of the standard input.
          -C callback       Evaluate CALLBACK each time QUANTUM lines are read.
          -c quantum        Specify the number of lines read between each call to CALLBACK.
    
        Arguments:
          ARRAY             Array variable name to use for file data.
    
        If -C is supplied without -c, the default quantum is 5000.  When
        CALLBACK is evaluated, it is supplied the index of the next array
        element to be assigned and the line to be assigned to that element
        as additional arguments.
    
        If not supplied with an explicit origin, mapfile will clear ARRAY before
        assigning to it.
    
        Exit Status:
        Returns success unless an invalid option is given or ARRAY is readonly or
        not an indexed array.
    

提交回复
热议问题