LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   add value to array in loop bash (https://www.linuxquestions.org/questions/programming-9/add-value-to-array-in-loop-bash-4175568056/)

bishop2001 01-27-2016 12:40 PM

add value to array in loop bash
 
Greetings
i have a loop as follows:

declare -a Array
var=1
cat ./some_file | while read line
do
some_command_where_a_value_is_returned
((var++))
done


i'd like to add the returned value to Array.
something like this below which isn't working. suggestions please? Thanks again
array+=("some_command_where_a_value_is_returned")

grail 01-27-2016 01:22 PM

Anything in a subshell is undone once returned to the parent shell (pipe into while is causing a subshell). Hence the array is once again empty.

Just a side note, you seem to have several questions on the go ... are you going to close any of the older ones?
Most seem related so it is hard to imagine you have moved on without solving the prior ones first. just a thought

bishop2001 01-27-2016 02:46 PM

hi i closed the other threads i had open. thanks.

Keith Hedger 01-27-2016 07:08 PM

Using the | creates pipe and a subshell as grail explained use redirection instead eg
Code:

var=1
while read
do
((var++))
done < <(cat ./somefile)
echo $var1


grail 01-28-2016 02:13 AM

Or just ditch cat altogether :)
Code:

while
do
  ...
done<somefile

./ not required as the default is to look in the current directory.

Ramurd 01-28-2016 02:23 AM

Since often in such loops I have to do something with stdin/stdout, which is already used by your loop (and thus can cause unpredictable behaviour), I tend to use another channel:

Code:

while read -u 9 line
do
.... stuff
done 9<somefile

now you can do stuff with stdin and stdout as usual.

Keith Hedger 01-28-2016 05:20 AM

Quote:

Originally Posted by grail (Post 5488478)
Or just ditch cat altogether :)
Code:

while
do
  ...
done<somefile

./ not required as the default is to look in the current directory.

Agreed I was just using the code the OP had already provided to demonstrate, also of course you can use any other command inside the <() construct not just cat, eg
Code:

...
done < <(top -bn1)
...

Which would send the output of a single 'top' run into the loop.
I just use './' as a matter of course just so it's obvious I am using a file/command in the current dir, just a habit and it does no harm.


All times are GMT -5. The time now is 08:56 AM.