Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash read array from an external file

Tags:

bash

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'
input[1]='username'
input[2]='example.com'
input[3]='/home/newuser' 

Now what I am trying to accomplish is to be able to read from var.txt from a script kinda like this:

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

now I know that wont work just using it for an example.

Thanks in Advance, Joe

like image 506
jmituzas Avatar asked Nov 29 '22 10:11

jmituzas


1 Answers

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.

like image 182
thejoshwolfe Avatar answered Dec 06 '22 09:12

thejoshwolfe