2

I have a shell script like this , i am reading a file and counting the line number. i got logs like 1,2,3,4.. etc from inside processsNumber function

#!/bin/bash

number=0;
processNumber () {
    ((number++));
    echo "$number";
}

grep -E '*' readme.txt | while read -r line ; do
    processNumber "$line";
done;
echo "And at last $number";

But it logs "And at last 0" , but i was expecting the last line number. Why its like that ? is it because gres reads a file a assync call hence echo has to be a callback to that.

Or is that global variable changes cannot be tracked outside the function.?

How to fix this with out changing the grep and pipe ?

NOTE: my target is not find the number of lines in the file , but to understand this

0

1 Answer 1

4

But it logs "And at last 0"

That is because you're calling processNumber function using a pipe which makes it execute in a sub shell not in the main shell hence in parent shell variable remains unchanged to 0.

UPDATE: To avoid creating pipe (and subshell) use for loop like this:

while read -r line; do
    processNumber "$line"
done < readme.txt
Sign up to request clarification or add additional context in comments.

7 Comments

is there a way to make callbacks in shell like javascriot callbacks ?
Shell doesn't have callback like JS has in String#replace but if you clarify what you want to do we can sure help. But I also request to not to change the question completely in doing do.
i need a method to how to fix this, without changing the pipe logic
ok check my updated answer for that.
Did this work out for you?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.