remove specified text from file

I am trying to write a script that kills old sessions, I've posted here over the past few days and the script is just about perfect except I want to be given the option to exclude specified PIDs from being killed. this is the entire script:

if [ -e /tmp/idlepids ]
then
rm /tmp/idlepids
fi
if [ -e /tmp/idlepidss ]
then
rm /tmp/idlepidss
fi
if [ -e /tmp/unwantedpids ]
then
rm /tmp/unwantedpids
fi
numusers=$(who -q | grep Total | tr -s " " | cut -d" " -f3)
echo Total number of sessions: ${numusers}
if test $numusers -gt 60; then
diff=$(expr $numusers - 60)
if test $diff -eq 1
then
echo "There is $diff too many sessions. Killing the oldest session."
else
echo "There are $diff too many sessions, killing the $diff oldest sessions:"
fi
who -u -H | sort -r -k6.2,6 | grep bhb | tr -s " " | cut -d" " -f7 >> /tmp/idlepids
head -$diff /tmp/idlepids >> /tmp/idlepidss
echo "About to kill the following sessions:"
while read PID; do who -u | grep $PID | sort -k4.2,6; done</tmp/idlepidss
#echo "Press ENTER to continue..."
#read enterKey
echo "Last chance to save PIDs..."
echo "Enter up to 9 PID numbers you want to keep alive: \c"
read pid1 pid2 pid3 pid4 pid5 pid6 pid7 pid8 pid9
cat /tmp/idlepidss | grep -v $pid1 | grep -v $pid2 | grep -v $pid3 | grep -v $pid4 | grep -v $pid5 | grep -v $pid6 | grep -v $pid7 | grep -v $pid8 | grep -v $pid9 > /tmp/unwantedpids

while read PID; do kill $PID; done</tmp/unwantedpids
echo "Sessions killed. Exiting"
else
echo "There are less than 60 users. Exiting"
fi
exit 1

It gives a bunch of grep usage errors
I tested grep -v on the command line and it works.

# cat /tmp/idlepidss
43532
35134
49276
# echo $pid1 $pid2 $pid3

# read pid1 pid2 pid3
43532 35134
# cat /tmp/idlepidss | grep -v $pid1 $pid2
grep: 0652-033 Cannot open 35134.
# set -o vi
# cat /tmp/idlepidss | grep -v $pid1 |grep -v $pid2
49276
#

Probably a quoting issue; if $pid2 is the empty string then you get a syntax error for grep -v $pid2 but it's easy to fix: grep -v "$pid2" with double quotes around the variable (always when using variables, as a strong recommendation). However, you also need to watch out for grep -v "" because it will remove all lines. As a workaround, you could use "${pid2:-nosuchstringmadam}" to replace an empty variable value with an unlikely default string.

As an aside, you can also simplify the long string of greps with egrep -v "$pid1|$pid2|$pid3" etc. And of course, cat file | grep something is always possible to write as grep something file (the purpose of cat is to catenate multiple files together; using it on a single file is usually misdirected).

Thanks a lot, worked great :slight_smile: