Jump to content
xisto Community
Sign in to follow this  
Inspiron

Bash - Reading File Line-by-line Problem?

Recommended Posts

Hey guys.. I'm new to Bash programming and I'm encountering this weird problem..
I'm trying to read a text file line-by-line and store into an array..
However, by using the WHILE-LOOP to read each line from file, the variables (normal var or arrays) doesn't seem to update..
The variables were automatically cleared upon exiting the WHILE-LOOP and revert back to it's previous state.

#!/bin/bashclear; echox=10echo "Original X: $x"i=0cat "test.txt" | while read FileLinedo   MyArray[$i]="$FileLine"   x=$(($x + 1))   echo "Array ($i): ${MyArray[$i]}"     i=$(($i + 1))doneechoecho "Array (*): ${MyArray[*]}"echo "No.of Elements: ${#MyArray[*]}"echo "Is X updated?: $x"echo
Contents of "test.txt"
line1 xline2 yline3 z
The output in the terminal was:
Original X: 10Array (0): line1 xArray (1): line2 yArray (2): line3 zArray (*):No.of Elements: 0Is X updated?: 10
You can see that variable X was not updated and reverted back to 10.

Are they ways or workarounds to get the variables updated..?

Share this post


Link to post
Share on other sites

@mra550

 

Bash is a shell. (Bourne Again Shell). It comes with linux/unix operating system. It is like DOS Command Prompt in Windows. Bash provides a scripting language which has branching and looping constructs similar to those found in C/C++.

 

Just like you can run commands like dir, del in DOS command prompt; you can run commands in bash shell. You can combine these commands with branching/looping contructs to create more powerful and complex commands.

 

I hope you can feel, what I am trying to say .. :)

 

@Inspiron

Hi,

 

Problem is that while loop is spawning a new shell to do the work. x in the sub-shell is incrementing but the x in the parent shell remains the same. when the sub-shell exits, you get to see the old value.

 

#!/bin/bashIFS=''file=( $( < test.txt ) )echo "file (*): ${file[*]}"echo "No. of elements: ${#file[*]}"

If you want to see the change; you may wish to see the following sample code.

 

#!/bin/bashfunction change() {	eval "$1=$(($1+1))"}x=10echo "Before change: $x"change xecho "After change: $x"

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.