Register
It is currently Thu Oct 23, 2014 9:46 am

array data not accessible outside of loop


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Sat Dec 10, 2011 1:34 pm   

Joined: Sat Dec 10, 2011 1:10 pm
Posts: 1
Below is a test script I was trying to use so that I could understand why the logic was not working in a larger script. While accessing and printing array data inside the while loop, everything is fine. Outside the loop, i guess everything is null?? The for loop that is meant to cycle through the array prints blank lines. The last two test echo statements after the call of the function in the main body also fail to output array information. The file addon_list_one_line.txt is a single line of strings that can be seen during the initial output below.

Can anyone explain to me what is wrong?

#!/bin/bash

addon_list=addon_list_one_line.txt

function test_function {
cat $addon_list|while read line
do
ADDON=( $line )
echo "\$line is $line"
echo "whole array is ${ADDON[@]}"
echo "first array item is ${ADDON[0]}"
echo "last array item is ${ADDON[14]}"
done
for a in {0..14}
do
echo "${ADDON[$a]}"
done
}

#main body

test_function
echo "last array item is ${ADDON[14]}"
echo "original_array = ${ADDON[@]}"

output of script:

> ./array_example2.sh ~/scripts/wow_addons
$line is auctioneer recount basic-minimap bison deadly-boss-mods dominos heal-bot-continued holy-power-notifier ice-hud omen-threat-meter postal prat-3-0 quartz quest-helper skada
whole array is auctioneer recount basic-minimap bison deadly-boss-mods dominos heal-bot-continued holy-power-notifier ice-hud omen-threat-meter postal prat-3-0 quartz quest-helper skada
first array item is auctioneer
last array item is skada
printing each array element individually...















last array item is
original_array =


Top
 Profile  
 PostPosted: Sun Dec 11, 2011 1:04 am   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 550
Hi,

the right hand part of a pipe is a subshell, thus variables assigned in it are not available from its parent.
plus, cat file | command is usually an uuoc!
try
Code:
while read line
do #any command
   :
done <file


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP