0

I am a new bash learner. I want to know, how to take a list of string from standard input? After taking all of the strings, I want to print them space separated.

Say the input is like the following:

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway

The output should be like:

Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway

I just can read a variable in bash and then can print it like the following:

read a
echo "$a"

Please, note that :

This question does not answer my question. it is mainly on traversing a declared array. but my case is handling the input and appending the array in runtime as well as detecting the EOF

3
  • cat /tmp/file_with_countires | awk '{printf("%s ", $0)}' Commented Jun 30, 2015 at 8:10
  • It is not from file, it is from standard input. @klerk Commented Jun 30, 2015 at 8:12
  • The question you referred is mainly on traversing a declared array. but my case is handling the input and appending the array in runtime as well as detecting the EOF @Identity1 Commented Jun 30, 2015 at 8:14

2 Answers 2

5

You can use read in a loop with a bash array:

countries=()
while read -r country; do
    countries+=( "$country" )
done
echo "${countries[@]}"

If used interactively, Ctrl-d terminates the loop, otherwise it will terminate once read fails (e.g. at EOF). Each country is printed on the same line.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming your list is a file (you can always save to a file):

my_array=( $(<filename) )
echo ${my_array[@]}

From standard input:

while :
do
read -p "Enter something: " country
my_array+="country"
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.