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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With