0

So I have a .txt file which contains a list of PIDs and I want to write a shell script to check which of those PIDs are active.

My File.txt looks like-

10414
10491
10632
10636
10623
10639

I want to read the file line by line and check if that particular PID is active or not and if not then remove only that PID from the file.

Vijay Shekhawat
  • 149
  • 2
  • 13

2 Answers2

1

Here inputFile is the source file containing pids

awk 'NR==FNR{p[$1]=$1;next} $2 in p{print $2}' inputFile <(ps -eaf) >inputFile.tmp && mv inputFile.tmp inputFile

Details:

Following will print the ps result for the process currently running which are also present in your file.

awk 'NR==FNR{p[$1]=$1;next} $2 in p' inputFile <(ps -eaf)

Following will create a tmp storage and create your desired file with only running pids.

>inputFile.tmp && mv inputFile.tmp inputFile
P....
  • 17,421
  • 2
  • 32
  • 52
0

Try this

#!/bin/bash

for pid in $( ps -e | grep -v 'PID' | cut -f 2 -d ' ' );
do
    for _pid in $( cat $1 );
    do
        if [ $_pid = $pid ];
        then
            echo $pid
        fi
    done
done

Usage: ./check_if_is_active.sh list_of_pid_to_check.txt

Kerkouch
  • 1,446
  • 10
  • 14