0

I have this code to parse PIDs from lsof output, As you can see echo $PID is working fine here, showing all PIDs, But I would like to append all PIDs to one variable ALL_PIDS, ( and used it then for killing all proces at once. Why is not working ?

this work

# lsof +d /var/log/ | tail -n +2 | awk ' { print $2 }' | uniq| while read PID; do echo $PID; done
940
1181
1603

this not work, I got empty line

# lsof +d /var/log/ | tail -n +2 | awk ' { print $2 }' | uniq| while read PID; do ALL_PIDS+=$PID; done
# echo $ALL_PIDS

#
andrew
  • 459
  • 5
  • 21
  • You don't need a loop, just pipe to `xargs kill`, or use the features of `lsof` directly. – tripleee Sep 23 '21 at 19:08
  • 2
    [BashFAQ #24](https://mywiki.wooledge.org/BashFAQ/024) – Charles Duffy Sep 23 '21 at 19:08
  • ok, I can do also this 1lsof +d /var/log/ | tail -n +2 | awk ' { print $2 }' | uniq| while read PID; do kill $PID; done`, but why not working append operation is my question ? – andrew Sep 23 '21 at 19:09
  • The FAQ link above explains it. So does the linked duplicate. Go read. (It's not that it doesn't work -- the append happens just fine -- but when the pipeline exits, all the shell state that was local to the processes in that pipeline is discarded). – Charles Duffy Sep 23 '21 at 19:09
  • You can easily avoid the `tail` and `uniq`; `awk 'NR>2 && !seen[$2]++ { print $2 }'` – tripleee Sep 23 '21 at 19:10
  • Mind, generating a _list of objects_ by appending to a _string_ has its own problems. Lists should be stored in arrays, not strings; [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050) discusses the problems one hits otherwise. – Charles Duffy Sep 23 '21 at 19:12

0 Answers0