Bash以声明方式定义要循环的列表
发布时间:2020-12-16 01:51:37 所属栏目:安全 来源:网络整理
导读:在bash中,我经常创建脚本,循环遍历我定义的字符串列表. 例如 for a in 1 2 3 4; do echo $a; done 但是我想定义列表(在循环之前保持它干净),以便它包含空格并且没有单独的文件: 例如(但这不行) read -r VAR HERElist item 1list item 2list item 3...HEREfo
在bash中,我经常创建脚本,循环遍历我定义的字符串列表.
例如 for a in 1 2 3 4; do echo $a; done 但是我想定义列表(在循环之前保持它干净),以便它包含空格并且没有单独的文件: 例如(但这不行) read -r VAR <<HERE list item 1 list item 2 list item 3 ... HERE for a in $VAR; do echo $a; done 上面的预期输出(我想): 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 如果您有这种需要,这还有一个额外的好处,即允许每个列表项包含空格. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |