Bash: can't build array in right side of pipe

2019-02-25 13:24发布

Anyone have a clue as to why this code is not working as expected?

$> svnTags=()
$> svn ls http://plugins.svn.wordpress.org/duplicate-post/tags/ | while read line; do slashless=$(sed 's#/$##g' <<< $line); echo "slashless - $slashless"; svnTags+=($slashless); done
slashless - 1.0
slashless - 1.1
slashless - 1.1.1
slashless - 1.1.2
slashless - 2.0
slashless - 2.0.1
slashless - 2.0.2
slashless - 2.1
slashless - 2.1.1
slashless - 2.2
slashless - 2.3
$> echo "$svnTags[@]"

Not giving any output, I'm expecting it to output the built array of the svn tags.

Second command broken out:

svn ls http://plugins.svn.wordpress.org/duplicate-post/tags/ | while read line; do
    slashless=$(sed 's#/$##g' <<< $line)
    echo "slashless - $slashless"
    svnTags+=($slashless)
done

2条回答
放我归山
2楼-- · 2019-02-25 13:42

Personally, I prefer to avoid while read when possible. I'd do it like this:

url=http://plugins.svn.wordpress.org/duplicate-post/tags/
IFS=$'\n' svnTags=($(svn ls "$url" | sed 's/^/slashless - /; s#/$##g'))

The results of declare -p svnTags are then:

declare -a svnTags='([0]="slashless - 0.3" [1]="slashless - 0.4" [2]="slashless - 0.5" [3]="slashless - 0.6" [4]="slashless - 0.6.1" [5]="slashless - 1.0" [6]="slashless - 1.1" [7]="slashless - 1.1.1" [8]="slashless - 1.1.2" [9]="slashless - 2.0" [10]="slashless - 2.0.1" [11]="slashless - 2.0.2" [12]="slashless - 2.1" [13]="slashless - 2.1.1" [14]="slashless - 2.2" [15]="slashless - 2.3" [16]="slashless - 2.4" [17]="slashless - 2.4.1")'
查看更多
Melony?
3楼-- · 2019-02-25 13:52

Because what happens after | is a subshell. Variables changed in a subshell do not propagate back to the parent shell.

Common workaround:

while read line ; do
    ...
done < <(svn ls http://...)
查看更多
登录 后发表回答