Bash read array from an external file

后端 未结 3 786
长情又很酷
长情又很酷 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 03:13

    If the whole var.txt file contains only Bash-compatible variable assignments as you indicated, you might just be able to source it, to make those variables available in a new Bash script:

    source var.txt
    
    useradd ${input[1]}
    

    This, however, will overwrite any existing variable with the same name. Command substitution can be used to avoid this, by selecting specific variables:

    input[1]="$(grep '^input\[1\]=' var.txt | sed "s|[^=]*='\(.*\)'|\1|")"
    

    It allows for renaming variables, although you will have to do this for each variable of interest. It essentially extracts the value of the variable from the var.txt file and assigns it to a new variable. See the grep manual page and the sed info page for more information on their use.

    Process substitution may allow for simpler expressions:

    source <(grep '^input\[[0-9]*\]=' var.txt)
    
    useradd ${input[1]}
    

    This would allow you to import only definitions of interest, although you have to watch for unwanted variable overwrites.

提交回复
热议问题