简体   繁体   中英

Strange Bash Variable Assignment Behaviour in For Loop

I'm assigning a variable inside a for loop where I make an output file name from the provided input.

I've never had any problems with arrays or for loops before but the behaviour is very strange. I've used similar for loops elsewhere in the code which all work fine. The code below works fine and the variable is assigned as expected.

count=1

for i in "${INPUT[@]}"
do
    local INPUT[$count]=`echo -n "$i" | sed 's/\(.\)/\1\n/g'`

    let count=count+1
done

That all works as expected, however, the code below does not work.

count=1

for i in "${INPUT[@]}"
do
    local OUTFILE[$count]="$i"

    let count=count+1
done

If I echo out the value of $INPUT[$count] or $i I get my expected result, however, when I echo out the value of $OUTFILE[$count] after assignment, it comes out as [1], [2], [3], etc. rather than person's name, person's name, person's name, etc.

It sounds like you are writing something like

echo $OUTFILE[$count]

when you should be writing

echo ${OUTFILE[$count]}

要将一个数组复制到另一个BASH数组中,您不需要循环,您可以执行以下操作:

OUTFILE=( "${INPUT[@]}" )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM