Re: OT - BASH question?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> Does anyone know of a GOOD bash list? If yes - I'll go there.
> 
> The following works:
>    while read line; do
>    ...
>    ...
>    done < somefile
>    ...
>    ...
> 
> How would one go about doing something similar replacing the file 
redirection
> with the output of a command? Before you say pipe it, that doesn't work
> because the pipe starts a subprocess and anything done inside the while 
loop
> is lost to the rest of the original process.
> 
> i.e.
>    ps -eo "%p" | while read line; do
>    ... # anything done here is
>    ... # lost to the original process
>    done
>    ... # Code here can't use anything
>    ... # done inside the while loop
> 
> Suggestions?

This is a bash limitation which BTW does not happen in ksh. But it doesn't 
have to limit you if you understand what it is you want.

Here's an example. Let's say you want to capture the pid data as above and 
send a kill to each of them. What you can't do is say:

typeset -a pidarray
ii=0
ps -eo "%p" | while read line 
do
   pidarray[ii]=$line
done

for ii in ${pidarray[$@]}
do
    echo "Killing $ii"
    kill -9 $ii
done

You can't do this because the instance of pidarray in the child process is 
different from the instance in the parent. So the solution is to capture 
the data you need from stdout:

typeset -a pidarray
pidarray=($(ps -eo "%p" | while read line
do
    echo $line
done))

Then just proceed to do what you want...

for i in ${pp[@]}
do
    echo "Killing $ii"
    kill -9 $ii
done

The trick is to just capture what you need.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net


[Index of Archives]     [Current Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Yosemite News]     [Yosemite Photos]     [KDE Users]     [Fedora Tools]     [Fedora Docs]

  Powered by Linux