Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am a new to Bash. I have an array taking input from standard input. I have to concatenate itself twice. Say, I have the following elements in the array:

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway

Now, The output should be:

Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway

My code is:

countries=()
while read -r country; do
    countries+=( "$country" )
done
countries=countries+countries+countries # this is the wrong way, i want to know the right way to do it
echo "${countries[@]}"

Note that, I can print it thrice like the code below, but it is not my motto. I have to concatenate them in the array.

countries=()
while read -r country; do
    countries+=( "$country" )
done
echo "${countries[@]} ${countries[@]} ${countries[@]}"
question from:https://stackoverflow.com/questions/31143874/how-to-concatenate-arrays-in-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
80 views
Welcome To Ask or Share your Answers For Others

1 Answer

First, to read your list into an array, one entry per line:

readarray -t countries

...or, with older versions of bash:

# same, but compatible with bash 3.x; || is to avoid non-zero exit status.
IFS=$'
' read -r -d '' countries || (( ${#countries[@]} ))

Second, to duplicate the entries, either expand the array to itself three times:

countries=( "${countries[@]}" "${countries[@]}" "${countries[@]}" )

...or use the modern syntax for performing an append:

countries+=( "${countries[@]}" "${countries[@]}" )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...