巴什声明定义一个列表循环 [英] Bash declaratively defining a list to loop on

查看:147
本文介绍了巴什声明定义一个列表循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中我经常做的脚本在哪里,我定义字符串列表我循环。

In bash I frequently make scripts where I loop over a list of strings that I define.

例如

for a in 1 2 3 4; do echo $a; done

不过,我想定义列表(循环之前,以保持它的清洁),以便它包含空格,用了一个单独的文件:

However I would like to define the list (before the loop to keep it clean) so that it contains spaces and with out a separate file:

例如。 (但是这不会工作)

e.g. (BUT THIS WILL NOT WORK)

read -r VAR <<HERE
list item 1
list item 2
list item 3
...
HERE

for a in $VAR; do echo $a; done

以上的预期结果(我想):

The expected output above (I would like):

list item 1
list item 2
list item 3
etc...

但你会得到:

list
item
1

我可以使用数组,但我将不得不指数每个元素在数组中(编辑阅读下面你可以追加到阵列的答案。我不知道你能的)。

如何他人定义声明bash中列出了与使用单独的文件呢?

对不起,我忘了提,我想在文件的热门for循环逻辑之前定义列表

推荐答案

数组不是那么难用:

readarray <<HERE
this is my first line
this is my second line
this is my third line
HERE

# Pre bash-4, you would need to build the array more explicity
# Just like readarray defaults to MAPFILE, so read defaults to REPLY
# Tip o' the hat to Dennis Williamson for pointing out that arrays
# are easily appended to.
# while read ; do
#    MAPFILE+=("$REPLY")
# done

for a in "${MAPFILE[@]}"; do
    echo "$a"
done

这有让每个列表项包含空格的好处是,你应该有这个需要。

This has the added benefit of allowing each list item to contain spaces, should you have that need.

这篇关于巴什声明定义一个列表循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆