如何读取 bash 中的字符串数组
how to read an array of strings in bash
我是一名新 bash
学习者。我想知道,如何从标准输入中获取字符串列表?获取所有字符串后,我想将它们 space 分开打印。
假设输入如下:
Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway
输出应该是这样的:
Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway
我只能读取 bash
中的一个变量,然后可以像下面这样打印它:
read a
echo "$a"
请注意:
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
您可以在带有 bash 数组的循环中使用 read
:
countries=()
while read -r country; do
countries+=( "$country" )
done
echo "${countries[@]}"
如果交互使用,Ctrl-d终止循环,否则一旦read
失败(例如在结尾)。每个国家都打印在同一行上。
假设你的列表是一个文件(你总是可以保存到一个文件):
my_array=( $(<filename) )
echo ${my_array[@]}
来自标准输入:
while :
do
read -p "Enter something: " country
my_array+="country"
done
我是一名新 bash
学习者。我想知道,如何从标准输入中获取字符串列表?获取所有字符串后,我想将它们 space 分开打印。
假设输入如下:
Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway
输出应该是这样的:
Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway
我只能读取 bash
中的一个变量,然后可以像下面这样打印它:
read a
echo "$a"
请注意:
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
您可以在带有 bash 数组的循环中使用 read
:
countries=()
while read -r country; do
countries+=( "$country" )
done
echo "${countries[@]}"
如果交互使用,Ctrl-d终止循环,否则一旦read
失败(例如在结尾)。每个国家都打印在同一行上。
假设你的列表是一个文件(你总是可以保存到一个文件):
my_array=( $(<filename) )
echo ${my_array[@]}
来自标准输入:
while :
do
read -p "Enter something: " country
my_array+="country"
done