Bash read array from an external file

后端 未结 3 782
长情又很酷
长情又很酷 2020-12-04 02:32

I have setup a Bash menu script that also requires user input. These inputs are wrote (appended to) a text file named var.txt like so:

input[0]=\'192.0.0.1\'         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 02:52

    Use bash's readarray statement. (It's the only way I can find to put spaces in array elements dynamically.) You'll need your var.txt file to simply contain the elements of the array, one on each line, not contain assignment statements.

    readarray -t input < var.txt
    

    For more info, try help readarray (which will then tell you to try help mapfile).

    Here's my test for it:

    echo -e "a\nb c\nd" > var.txt
    readarray input < var.txt 
    for item in "${input[@]}"; do echo $item; done
    

    prints:

    a
    b c
    d
    

    Note: doing cat var.txt | readarray -t input doesn't work. I think it's because the input variable is scoped out of reach.

提交回复
热议问题