On 7/26/22 8:41 AM, Andrei Borzenkov wrote:
On 26.07.2022 15:25, kf wrote:
Obviously I've reduced and rewitten it to better point out the problem in this script. The question is, how should the variable "count" be declared so that it isn't treated as two, completely different variables (with exactly the same name)?
It has nothing to do with declaration or scope.
If you want to try to run it, it takes a filename as an commandline argument.
======================== #!/bin/bash
#How to declare the variable "count"??? count=0
cat $1 | while read line do count=$((count+1)) echo -n "$count " done
Right hand of pipe is executed in separate process (subshell), so any changes done there do not affect main shell process.
Yes, I was aware that another process started with "while...". But is there no way to specify a variable type which can access that other process? There can be merit in isolating variables, even when they have the same name, but as my case here shows, there are also times when a variable's value should be accessible throughout the body of code, e.g., when in C a global or static variable is used. Is that simply impossible in bash?
You can redirect from file instead
while read ... ... done < $1
echo echo File $1 has $count lines.
========================
That's a good suggestion. Thanks.
Thanks.