Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept multiple lines of input in a bash script

I am in the middle of writing a bash script. The pending point I am stuck with is how to accept multiple inputs from the user at a time.

To be specific, a user must be able to input multiple domain names when the script asks to enter the input.

Example, script running portion:

Enter the domain names :

and user must be able to enter the domain names line by line either by entering each of them manually or he/she just have to copy domain names list from somewhere and able to paste it in the script input, like as follows:

domain1.com
domain2.com
domain3.com
domain4.com

Is it possible?.

like image 252
vjwilson Avatar asked Dec 18 '22 14:12

vjwilson


2 Answers

Yes, you can: use readarray:

printf "Enter the domain names: "
readarray -t arr
# Do something...
declare -p arr

The last line above just documents what bash now sees as the array.

The user can type or copy-and-paste the array names. When the user is done, he types Ctrl-D at the beginning of a line.

Example:

$ bash script
Enter the domain names: domain1.com
domain2.com
domain3.com
domain4.com
declare -a arr='([0]="domain1.com" [1]="domain2.com" [2]="domain3.com" [3]="domain4.com")'
like image 168
John1024 Avatar answered Feb 01 '23 21:02

John1024


Use loop:

#!/bin/bash

arrDomains=()
echo "Enter the domain names :"

while read domain
do
    arrDomains+=($domain)
    # do processing with each domain
done

echo "Domain List : ${arrDomains[@]}"

Once you have entered all domain names press ctrl + D to end of input.

like image 43
sat Avatar answered Feb 01 '23 20:02

sat