簡體   English   中英

Bash以聲明方式定義要循環的列表

[英]Bash declaratively defining a list to loop on

在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循環邏輯之前定義文件頂部的列表

您可以像這樣使用“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

數組不是那么難用:

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

這里有更好的答案,但您也可以分別對\\n進行讀取,並使用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

如果你可以使用while循環而不是for循環,你可以使用while read結構和“here document”:

#!/bin/bash

while read LINE; do
    echo "${LINE}"
done << EOF
list item 1
list item 2
list item 3
EOF

ref: `cat << EOF`如何在bash中運行?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM