Reputation: 733
I'm trying to take the input from the user into an array but Shell is accepting user input separated by spaced. Is there any way to accept the user input given separately in each line. My code below:
#!/bin/bash
echo "enter the servers names..."
read -a array
for i in "${array[@]}"
do
echo $i
done
exit 0
Input:
hello world
I want to the input to be taken as below (in two different lines):
hello
world
Kindly help. Thanks.
Upvotes: 1
Views: 100
Reputation: 67
#!/bin/bash
echo "enter the servers names..."
read -a array -d '\n'
for i in "${array[@]}"
do
echo $i
done
exit 0
or
#!/bin/bash
echo "enter the servers names..."
readarray array
for i in "${array[@]}"
do
echo $i
done
exit 0
Upvotes: -1
Reputation: 4704
According to help read:
Reads a single line from the standard input, or from file descriptor FD...
This loop would do instead:
echo "enter the servers names..."
i=0
until false; do
read server
[ -z "$server" ] && break
let i=i+1
array[$i]="$server"
done
for i in "${array[@]}"; do
echo $i
done
exit 0
The loop will exit on an empty line or EOF (ctrl-D).
Example session terminated by empty line:
@server:/tmp$ ./test.sh
enter the servers names...
se1
se2
se3se1
se2
se3
Example session terminated by EOF on the empty line after se2:
@server:/tmp$ ./test.sh
enter the servers names...
se1
se2
se1
se2
Please note that I check for an empty string while reading the names; but it is possible to check for empty strings (or whatever else) in any loop, for example while printing them or doing other computations.
Upvotes: 1
Reputation: 2308
You can specify the delimiter of read
to stop reading, rather than newline. (read man page)
-d delim continue until the first character of DELIM is read, rather than newline
For example:
read -d':' -a array
If you want there is no delimiter to input, you can use a loop to read into the elements of the array, then check whether the input is null string or not.
i=0
read "array[$i]"
while [ "${array[$i]}" ];
do
let "i = i+1"
read "array[$i]"
done
So the input will be
hello
world
# > there is one more empty line
Upvotes: 1