Jump to content



Welcome to KnowledgeSutra - Dear Guest , Please Register here to get Your own website. - Ask a Question / Express Opinion / Reply w/o Sign-Up!
- - - - -

Bash - Reading File Line-by-line Problem?


2 replies to this topic

#1 Inspiron

    Trap Grand Marshal Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPip
  • 1,204 posts

Posted 29 January 2010 - 02:52 AM

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/bash

clear; echo
x=10
echo "Original X: $x"
i=0
cat "test.txt" | while read FileLine
do
   MyArray[$i]="$FileLine"
   x=$(($x + 1))
   echo "Array ($i): ${MyArray[$i]}"
  
   i=$(($i + 1))
done

echo
echo "Array (*): ${MyArray[*]}"
echo "No.of Elements: ${#MyArray[*]}"
echo "Is X updated?: $x"
echo
Contents of "test.txt"
line1 x
line2 y
line3 z
The output in the terminal was:
Original X: 10
Array (0): line1 x
Array (1): line2 y
Array (2): line3 z

Array (*):
No.of Elements: 0
Is 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..?

#2 mra550

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 239 posts

Posted 29 January 2010 - 03:04 AM

actually I don't know about bash is it also a programming language? like C++? what are the difference ?

#3 manish-mohania

    Member [Level 1]

  • Kontributors
  • PipPipPipPip
  • 55 posts

Posted 29 January 2010 - 04:45 PM

@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/bash

IFS='
'
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/bash

function change() {
	eval "$1=$(($1+1))"
}

x=10
echo "Before change: $x"
change x
echo "After change: $x"





Reply to this topic


This post will need approval from a moderator before this post is shown.

  


1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users