gpt4 book ai didi

arrays - Bash 在 while 循环中构建数组(不持久)?

转载 作者:行者123 更新时间:2023-12-05 01:44:06 24 4
gpt4 key购买 nike

<分区>

考虑这个例子,比如说,test.sh:

cat > test.txt <<'EOF'
test 1
test 2
test 3
EOF

declare -a myarr
declare -p myarr # "declare: myarr: not found"
myarr=()
declare -p myarr # "declare -a myarr='()'"
#for (( i=1; i<=3; i++ )); do # ok
sed -n 's!test!TEST!p' test.txt | while read i; do # not preserved ?!
myarr=("${myarr[@]}" "pass $i")
declare -p myarr
done
declare -p myarr # "declare -a myarr='()'" ?!

如果我取消注释 for ((... 行,并注释 sed -n ... 行,那么 bash 测试的输出。 sh 符合预期:

test.sh: line 8: declare: myarr: not found
declare -a myarr='()'
declare -a myarr='([0]="pass 1")'
declare -a myarr='([0]="pass 1" [1]="pass 2")'
declare -a myarr='([0]="pass 1" [1]="pass 2" [2]="pass 3")'
declare -a myarr='([0]="pass 1" [1]="pass 2" [2]="pass 3")'

但是,如果我按发布的方式运行脚本,则 myarr 会构建在 while 循环中,但一旦超出循环,它就是空的:

test.sh: line 8: declare: myarr: not found
declare -a myarr='()'
declare -a myarr='([0]="pass TEST 1")'
declare -a myarr='([0]="pass TEST 1" [1]="pass TEST 2")'
declare -a myarr='([0]="pass TEST 1" [1]="pass TEST 2" [2]="pass TEST 3")'
declare -a myarr='()'

那么,为什么 myarr 在这种情况下(在 while 循环中,或者更确切地说,在 while 循环之后)是空的——我如何让它保持它的值?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com