简体   繁体   English

如何在bash shell脚本中读取多行输入到数组中

[英]how to read multiline input into an array in bash shell script

Is this a correct way to read multi line input into an array in bash? 这是在bash中将多行输入读入数组的正确方法吗?

arr=( $(cat) ); 
echo "{arr[@]}" 

I put this line into a script and I tried to read multiple input by hitting return key after each line but the script keeps on taking the input and does not print the elements of the array by coming to the second line, when I press ctrl C at the input console the script terminates. 我把这一行放到一个脚本中,我尝试通过在每一行之后按回车键来读取多个输入,但是脚本继续接受输入并且当我按下ctrl C时不会通过到达第二行来打印数组的元素在输入控制台上脚本终止。 Please suggest if that the correct way to read multi line input from the command line? 请建议从命令行读取多行输入的正确方法是否正确?

Several points to address: 要点几点:

First, don't use Ctrl-C but Ctrl-D to end the input: Ctrl-C will break the script (it sends the SIGINT signal), whereas Ctrl-D is EOF (end of transmission). 首先,不要使用Ctrl-C而是使用Ctrl-D来结束输入:Ctrl-C将破坏脚本(它发送SIGINT信号),而Ctrl-D是EOF(传输结束)。

To print the array, one field per line, use 要打印数组,每行一个字段,请使用

printf '%s\n' "${arr[@]}"

Now, the bad way: 现在,糟糕的方式:

arr=( $(cat) )
printf '%s\n' "${arr[@]}"

This is bad since it's subject to word splitting and pathname expansion: try to enter hello word or * and you'll see bad things happen. 这很糟糕,因为它受到单词拆分和路径名扩展的影响:尝试输入hello word* ,你会看到坏事发生。

To achieve what you want: with Bash≥4 you can use mapfile as follows: 要达到你想要的效果:使用Bash≥4你可以使用mapfile如下:

mapfile -t arr
printf '%s\n' "${arr[@]}"

or, with legacy Bash, you can use a loop: 或者,使用传统Bash,您可以使用循环:

arr=()
while IFS= read -r l; do
    arr+=( "$l" )
done
printf '%s\n' "${arr[@]}"

If you want to print each line as it's typed, it's probably easier to use the loop version: 如果要打印每行的类型,可能更容易使用循环版本:

arr=()
while IFS= read -r l; do
    printf '%s\n' "$l"
    arr+=( "$l" )
done

If you're feeling adventurous, you can use mapfile 's callback like so: 如果您喜欢冒险,可以使用mapfile的回调,如下所示:

cb() { printf '%s\n' "$2"; }
mapfile -t -c1 -C cb arr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM