Results 1 to 4 of 4
I'm running a command via the ``'s and I read this into a string. This value changes every few seconds. I then have a loop that parses that string and ...
- 11-10-2009 #1Just Joined!
- Join Date
- Oct 2009
- Posts
- 6
Bash Script: Need to read value from array in loop
I'm running a command via the ``'s and I read this into a string. This value changes every few seconds. I then have a loop that parses that string and I grab the relevant information using awk and I store it in an array.
How do I read back that array after the loop?
Ie.
Code:count=0 declare -a LIST `getCurrentNames.sh` | while read LINE; do AP_LIST[$count]="$DATE $LINE " count=$[$count+1] done echo "19th item is ${AP_LIST[11]}"
- 11-10-2009 #2Just Joined!
- Join Date
- Jan 2007
- Location
- Tamil Nadu, India
- Posts
- 18
Hi,
You can loop through the array from 0 to arraysize-1 and access the contents using $AP_LIST[index].
The arraysize can be found using ${#AP_LIST[*]}
- 11-10-2009 #3Just Joined!
- Join Date
- Oct 2009
- Posts
- 6
I thought a loop forked into another process though so I'd be out of scope?
- 11-15-2009 #4Just Joined!
- Join Date
- Nov 2009
- Posts
- 2
#!/bin/bash
# Variables modified in a while loop do not propagate to the parent because the loop's commands run in a subshell. This can make it difficult to track down bugs.
cmd="cat /etc/passwd"
last_line='NULL'
$cmd | while read line; do
last_line="${line}"
done
# This will output 'NULL'
echo "${last_line}"
# Using process substitution allows redirecting output but puts the commands in an explicit subshell rather than the implicit subshell that bash creates for the while loop.
last_line='NULL'
while read line; do
last_line="${line}"
done < <($cmd)
# This will output the last line of output from the command
echo "${last_line}"


Reply With Quote
