2

I am working on a script to delete users from text file. However, before deleting, I want to check if any process by a user is running and if running then kill all the processes and delete. Here's how I'm doing this:

    if 
   #user doesn't exists then print user not exist
else
pids = `ps U "$name" -o pid | head -n -1` 
    if [ -n "$pids" ]
    then
    for pid in $pids
    do
        sudo kill -KILL $pid
    done
fi


     sudo userdel

 $name -r -f    
    echo     


       echo "The user - $name - has been deleted!"
    echo
    fi
    done < "$fname"                         # double-quote fname
    echo

So, basically its a loop to delete users and in that an if statement to make sure no process is being run by a user and if its being run then force close processes and delete user.

However, Its not working and it says pids: command not found.. Any solution, how to fix it?

2

You have the following code:

pids = `ps U "$name" -o pid | head -n -1`

bash is picky about whitespace, here. Simply remove the spaces from pids = ... and it will work as intended:

pids=`ps U "$name" -o pid | head -n -1`
  • Thank you!! Programming gets really annoying sometimes, when you make a mistake like that.. Thanks for saving my life :D – Umair Dec 4 '14 at 23:58
2

Few things:

1) You cannot have a space around the = in shell script variable assignment. pids = ... should be pids=....
2) kill can accept multiple PIDs. You don't need a for pid in $pids ... loop. (though with the next item, this is irrelevant)
3) Your code can be drastically simplified by doing:

pkill -KILL -U "$name"

There is no need to check if the user has any processes running. If there aren't any, the command does nothing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.