Register
It is currently Thu Aug 21, 2014 2:00 pm

bash forgets array-value


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Fri Mar 19, 2010 5:02 pm   

Joined: Fri Mar 19, 2010 4:53 pm
Posts: 2
hi there,

i'm not very familiar with bash and array, but i wrote some bash scripts with arrays and they always worked.
but now, i'm totally confused, i've no more ideas where the problem is...

the following simple lines are working, but in the last line, the value from the array is "". means empty. why (?)...
by the way: i've a chain "temp" in the iptables-rules for temporary usage...

##################################
#!/bin/bash
clear

i=0

sudo iptables-save | egrep "\-A temp" | awk -F "^\-A " '{print$2}' | while read input; do
let i=i+1
value[$i]=$input
echo "[$i] ${value[$i]}" <--- here the allay prints the correct value
done

echo
i=2
echo "[$i] ${value[$i]}" <--- here the array is empty
###################################


any ideas?
thank you for any help...

-joadoor-


Top
 Profile  
 PostPosted: Fri Mar 19, 2010 9:19 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 535
it's common case as you create the array into a pipe, which is a subshell; and subshells don't export their variables to the main shell.
Code:
#!/bin/bash

while read input
do arr[i++]="$input"
done < <(sudo iptables-save | sed -n 's/^-A \(temp.*\)/\1/p')

printf '%s\n' "${arr[@}"
If you use Bash 4, you could use mapfile builtin, instead of this while loop


Top
 Profile  
 PostPosted: Sat Mar 20, 2010 5:55 am   

Joined: Fri Mar 19, 2010 4:53 pm
Posts: 2
ah thanks.
with the "to-do" at the end of the while-read loop it works!

-joadoor-


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

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 8 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:  


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