Bash以声明方式定义要循环的列表
在bash中,我经常编写脚本,在脚本中循环定义的字符串列表 e、 g 但是,我希望定义列表(在循环之前保持其干净),使其包含空格,而不包含单独的文件: e、 g.(但这行不通) 但你会得到:Bash以声明方式定义要循环的列表,bash,loops,Bash,Loops,在bash中,我经常编写脚本,在脚本中循环定义的字符串列表 e、 g 但是,我希望定义列表(在循环之前保持其干净),使其包含空格,而不包含单独的文件: e、 g.(但这行不通) 但你会得到: list item 1 我可以使用数组,但我必须为数组中的每个元素编制索引(编辑下面的阅读答案,因为你可以附加到数组中..我不知道你可以) 其他人如何在不使用单独文件的情况下在bash中以声明方式定义列表? 抱歉,我忘了提到我想在for循环逻辑之前在文件顶部定义列表,您可以使用如下“HERE Docume
list
item
1
我可以使用数组,但我必须为数组中的每个元素编制索引(编辑下面的阅读答案,因为你可以附加到数组中..我不知道你可以)
其他人如何在不使用单独文件的情况下在bash中以声明方式定义列表?
抱歉,我忘了提到我想在for循环逻辑之前在文件顶部定义列表,您可以使用如下“HERE Document”:
while read a ; do echo "Line: $a" ; done <<HERE
123 ab c
def aldkfgjlaskdjf lkajsdlfkjlasdjf
asl;kdfj ;laksjdf;lkj asd;lf sdpf -aa8
HERE
在读取一个文件时;做回显“行:$a”;完成当您可以使用while
循环而不是for
循环时,您可以使用while read
构造和“here document”:
#/bin/bash
读行时;做
回显“${LINE}”
done数组使用起来并不难:
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
readarray这里有更好的答案,但是您也可以使用IFS
环境变量在for
循环中,在中临时将变量分隔为换行,而不是空格
read -d \n -r VAR <<HERE
list item 1
list item 2
list item 3
HERE
IFS_BAK=$IFS
IFS="\n"
for a in $VAR; do echo $a; done
IFS=$IFS_BAK
read-d\n-r VAR如果您还指定了您尝试的内容如何无效,则会更有帮助。@解开我更新了问题。MAPFILE
正确吗?我只是想知道readarray
没有被引用。对不起,我应该说清楚的。如果未为readarray
指定数组,则默认情况下使用MAPFILE
。(mapfile
是readarray
命令的另一个名称。)我最喜欢@chepner的答案,因为我想在for循环之前定义列表/数组。我不介意它需要一个更新的bash作为我自己的用途。我已经更新了,如果你发现自己使用的是一个旧bash(例如Mac OS X附带的bash),我会快速替换readarray
。我很熟悉这一点,只是我想在for循环之前定义我的列表。与公认的答案相反,这种方法也适用于Mac OS X!我不知道您可以附加到数组,这就是为什么:)
while read a ; do echo "Line: $a" ; done <<HERE
123 ab c
def aldkfgjlaskdjf lkajsdlfkjlasdjf
asl;kdfj ;laksjdf;lkj asd;lf sdpf -aa8
HERE
#!/bin/bash
while read LINE; do
echo "${LINE}"
done << EOF
list item 1
list item 2
list item 3
EOF
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
while read -r line
do
var+=$line$'\n'
done <<EOF
foo bar
baz qux
EOF
while read -r line
do
echo "[$line]"
done <<<"$var"
array+=(value)
for item in "${array[@]}"
do
something with "$item"
done
read -d \n -r VAR <<HERE
list item 1
list item 2
list item 3
HERE
IFS_BAK=$IFS
IFS="\n"
for a in $VAR; do echo $a; done
IFS=$IFS_BAK