Array Variable being Assigned Values in Loop, But Gone when Loop Completes???


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Array Variable being Assigned Values in Loop, But Gone when Loop Completes???
# 1  
Old 10-18-2012
Array Variable being Assigned Values in Loop, But Gone when Loop Completes???

Hello All,

Maybe I'm Missing something here but I have NOOO idea what the heck is going on with this....?

I have a Variable that contains a PATTERN of what I'm considering "Illegal Characters". So what I'm doing is looping
through a string containing some of these "Illegal Characters". Now when these chars are found I add them to the Array
variable, and on the very next line (while still in the same if statement, inside the loop) I print the Array Element which
shows the correct value inside that particular element.

Now after the loop completes I'm trying to print the array with a 'for' loop and for some reason its treating the array as
if it were empty, and I have NO idea why this is happening...?

Here's the Section that isn't working correctly:
Code:
#!/bin/bash

declare -a FOUND_CHARS

ILLEGAL_CHARS="[\|\`\&\>\<\'\\\"\{\}\;\!]"    #--> CONTAINS ANY 1 OF:  | ` & > < ' \ " \ \ { } ; !
ILLEGAL_CHARS_2="\[|\]"                       #--> CONTAINS ANY 1 OF:  [  ]

### FOUND 6 Total Illegal Characters in this Test String "$MY_STR"
# CHARS ARE: {, }, &, <, >, and !
MY_STR="{SOME & STRING WITH ! A COUPLE ILLEGAL <CHARS>}"
echo -e "MY_STR = \"$MY_STR\""

count=0
echo -n "$MY_STR" | while read -n 1 char
 do
    if [[ "$char" =~ $ILLEGAL_CHARS  || "$char" =~ $ILLEGAL_CHARS_2 ]]
     then
        FOUND_CHARS[$count]="$char"
        echo -ne "  ILLEGAL char --> \"$char\"\n"
        echo -ne "FOUND_CHARS[$count] --> \"${FOUND_CHARS[$count]}\"\n"
        let count++
    else
        echo -ne "\tLEGAL CHARACTER --> \"$char\"\n"
    fi
done

echo -e "\n\n"

for sym in ${FOUND_CHARS[@]}
echo "Array Contains:"
 do
    echo -e "\tsym == $sym"
done

Below is the Output.
The Output from the "while" loop is CORRECT. But then after that "while" loop is done, then it's the "for" loop's turn and it
prints NOTHING...

Here's the Output:
Code:
MY_STR = "{SOME & STRING WITH ! A COUPLE ILLEGAL <CHARS>}"


  ILLEGAL char --> "{"
FOUND_CHARS[0] --> "{"
    LEGAL CHARACTER --> "S"
    LEGAL CHARACTER --> "O"
    LEGAL CHARACTER --> "M"
    LEGAL CHARACTER --> "E"
    LEGAL CHARACTER --> ""
  ILLEGAL char --> "&"
FOUND_CHARS[1] --> "&"
    LEGAL CHARACTER --> ""
    LEGAL CHARACTER --> "S"
    LEGAL CHARACTER --> "T"
    LEGAL CHARACTER --> "R"
    LEGAL CHARACTER --> "I"
    LEGAL CHARACTER --> "N"
    LEGAL CHARACTER --> "G"
    LEGAL CHARACTER --> ""
    LEGAL CHARACTER --> "W"
    LEGAL CHARACTER --> "I"
    LEGAL CHARACTER --> "T"
    LEGAL CHARACTER --> "H"
    LEGAL CHARACTER --> ""
  ILLEGAL char --> "!"
FOUND_CHARS[2] --> "!"
    LEGAL CHARACTER --> ""
    LEGAL CHARACTER --> "A"
    LEGAL CHARACTER --> ""
    LEGAL CHARACTER --> "C"
    LEGAL CHARACTER --> "O"
    LEGAL CHARACTER --> "U"
    LEGAL CHARACTER --> "P"
    LEGAL CHARACTER --> "L"
    LEGAL CHARACTER --> "E"
    LEGAL CHARACTER --> ""
    LEGAL CHARACTER --> "I"
    LEGAL CHARACTER --> "L"
    LEGAL CHARACTER --> "L"
    LEGAL CHARACTER --> "E"
    LEGAL CHARACTER --> "G"
    LEGAL CHARACTER --> "A"
    LEGAL CHARACTER --> "L"
    LEGAL CHARACTER --> ""
  ILLEGAL char --> "<"
FOUND_CHARS[3] --> "<"
    LEGAL CHARACTER --> "C"
    LEGAL CHARACTER --> "H"
    LEGAL CHARACTER --> "A"
    LEGAL CHARACTER --> "R"
    LEGAL CHARACTER --> "S"
  ILLEGAL char --> ">"
FOUND_CHARS[4] --> ">"
  ILLEGAL char --> "}"
FOUND_CHARS[5] --> "}"



Array Contains:

As you can see in the Output, the 'while' the loop is looping through the string and it is printing the Illegal
Characters that it finds, and you can see that the variable inside the loop DOES contain the values...

So why is the array empty after the loop has completed?
Any thoughts would be much appreciated!


Thanks in Advance,
Matt

---------- Post updated at 04:45 PM ---------- Previous update was at 03:55 PM ----------

UPDATE:

Well this look like it has something to do with my "while" loop...
Maybe something like it's spawning a sub-process so when it returns from the sub-process that Array doesn't exist anymore?

If I put the text into a file and loop using this construct (below) instead of what I have now, the array contains the data
after it completes.

NEW LOOP CONSTRUCT:
Code:
MY_FILE="~/temp_textFile.txt"
echo "$MY_STR" > $MY_FILE

while read -n 1 char
 do
           ...... CODE .....
done < $MY_FILE

How can I do this without printing to a file first?
Seems like too much work for something as simple as looping through a string character-by-character..?

Thanks,
Matt

Last edited by mrm5102; 10-18-2012 at 05:10 PM..
# 2  
Old 10-18-2012
Code:
echo -n "$MY_STR" | while read ...

The main shell forks off a copy of itself to run while read independently of the echo so they can both run while connected by a pipe. The copy, or "sub-shell", runs successfully, setting all your variables and such as you please, until the pipe runs out of information and returns EOF. Then the loop quits.

Then the subshell dies. Control is returned to the main shell, which remains unchanged. You set all your variables in the subshell, not the main one.

In short: It's the pipe that does it. Your shell and everything behind the pipe are different processes and don't share variables.

Pipes are overkill if you have substring operators anyway. This way of getting a single character ought to work identically in bash and ksh:

Code:
N=0

while [ "$N" -lt "${#STRING}" ]
do
        echo "${STRING:$N:1}"
        let N=N+1
done

This User Gave Thanks to Corona688 For This Post:
# 3  
Old 10-18-2012
Hey Corona, thanks for the reply!

Thanks, thats kinda what I had read... About the forking.

I'm not at my desk anymore, but as soon as I get in tomorrow
I'll give it a try and post back with my results.

Would it also be possible to set the IFS to something like "."
or "*" and then do the for loop like this:
Code:
IFS="*"
for char in "$MY_STR"
 do
         ..... Code ......
done

Would something like that work too?

Thanks Again,
Matt
# 4  
Old 10-18-2012
Afraid not. "${STRING:$N:1}" works fine, though.
This User Gave Thanks to Corona688 For This Post:
# 5  
Old 10-18-2012
or if your old ksh (ksh88) doesn't support the '${STRING:n:m}' paradigm:
Code:
#!/bin/ksh
MyString=abcde
i=0
while (( i++ < ${#MyString} ))
do
   char=$(expr substr "$MyString" $i 1)
   echo "<$char>"
done

This User Gave Thanks to vgersh99 For This Post:
# 6  
Old 10-19-2012
Hey Corona, thanks again for the reply.

Ok, thanks for the clarification...


Hey vgersh99, thanks for your reply.

Cool, another good example. Thanks!


Thanks Again for your Replies,
Matt

---------- Post updated at 10:00 AM ---------- Previous update was at 09:29 AM ----------

Hey Corona, just gave your example a try and it works perfectly..!


Thanks Again,
Matt
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Array not printing values if used in a loop

Hello! I'm making an English to Morse Code translator and I was able to mostly get it all working by looking through older posts here; however, I have one small problem. When I run it it's just printing spaces for where the characters should be. It runs the right amount of times, and if I try... (3 Replies)
Discussion started by: arcoleman10
3 Replies

2. Shell Programming and Scripting

Convert values in an array using a loop

I have a headerless array of 1000 columns x 100000 rows. The array only contains 4 values; 0/0, 0/1, 1/1, ./. Here I am showing the 1st 3 rows and columns of the input array 0/0 0/0 1/1 0/1 0/1 0/1 0/0 ./. 0/0 0/0 0/0 0/0 I would like to convert the values in... (9 Replies)
Discussion started by: Geneanalyst
9 Replies

3. Shell Programming and Scripting

How to swap the values in array using for loop?

array=( 8 5 6 2 3 4 7 1 9 0 ) for i in "${array}" do echo $i done # i need the output like this by swapping of array values 0 9 1 7 4 3 2 6 5 8 (7 Replies)
Discussion started by: Meeran Rizvi
7 Replies

4. Shell Programming and Scripting

Variable values within for loop

Hi All I am trying to fetch the size of three files into three separate variables within a for loop and am doing something like this: for i in ATT1 ATT2 ATT3 do size_$i=`ls -ltr $i | awk '{print $5}'` echo ${size_$i} done but am getting the below error: ksh: size_ATT1=522: not... (3 Replies)
Discussion started by: swasid
3 Replies

5. Shell Programming and Scripting

awk loop using array:wish to store array values from loop for use outside loop

Here's my code: awk -F '' 'NR==FNR { if (/time/ && $5>10) A=$2" "$3":"$4":"($5-01) else if (/time/ && $5<01) A=$2" "$3":"$4-01":"(59-$5) else if (/time/ && $5<=10) A=$2" "$3":"$4":0"($5-01) else if (/close/) { B=0 n1=n2; ... (2 Replies)
Discussion started by: klane
2 Replies

6. Shell Programming and Scripting

While loop - how to run processes one after another (2nd starts after first completes, and so on)

I'm a programming noob. I'm trying to run a memory intensive process for many files. But when I use the following script, it runs fine for the first 5-7 files, then runs out of memory. Monitoring the output files, it's clear the processes are going on in parallel. Once 5-7 of the files are being... (18 Replies)
Discussion started by: pathunkathunk
18 Replies

7. Shell Programming and Scripting

Assigning values to an array via for/while loop

I need to do something like this: for i in 1 2 3 4 5; do arr=$(awk 'NR="$i" { print $2 }' file_with_5_records) done That is, parse a file and assign values to an array in an ascending order relative to the number of record in the file that is being processed on each loop. Is my... (2 Replies)
Discussion started by: fiori_musicali
2 Replies

8. Shell Programming and Scripting

How to use array values after the loop.

- I m retreving values from database and wish to use those values later in my shell script. I m placing these values in an array da_data but outside loop array is empty.Problem is its treating array as local inside loop hence array is empty outside loop. Plz go through the script and suggest how... (1 Reply)
Discussion started by: Devesh5683
1 Replies

9. Shell Programming and Scripting

getting values from variable in a loop

I have a set of variables: f1="./someFolder" . . f10="./someOtherFolder" And I'm trying to use the following loop for (( i = 0; i <= 10; i++ )) do temp=f$i done I'm trying the get the values from my set of variable to make directories, but I can't seem the get those value... (3 Replies)
Discussion started by: kriuz
3 Replies

10. UNIX for Dummies Questions & Answers

For Loop and concetnating values in a variable

Hi, I have file abc.txt which has keys and emails addresses abc.txt emailkey1:sam@abc.com emailkey1:tom@abc.com emailkey2:rqw@abc.com emailkey2:tut@abc.com I have a shell script where i pass key as the parameter and i want all the email addresses within that key concatenated by a comma... (21 Replies)
Discussion started by: samit_9999
21 Replies
Login or Register to Ask a Question