[Bash] Kill command

The kill command sends a signal to a process, usually to terminate the process.

kill PID

This command sends the SIGTERM signal to the process with the given PID.

Common Options:

-l: List all signal names.
-9 or -KILL: Send the SIGKILL signal to forcefully terminate a process.
-15 or -TERM: Send the SIGTERM signal to gracefully terminate a process (default).

# Terminate a process with PID 1234:
kill 1234

# Forcefully terminate a process with PID 1234
kill -9 1234

# List all signal names
kill -l

Pratice

# Find the process IDs and names of the zsh process
$ pgrep -l zsh
1092 zsh

# Find the process IDs of processes for the current user:
pgrep -u $USER
#!/bin/zsh

echo "Enter the process name to terminate: "
read process_name

pids=$(pgrep "$process_name")

# if pids length is 0
if [ -z "$pids" ]; then 
  echo "No process found with the name $process_name."
  exit 1
fi

echo "Found the following PIDs for $process_name: $pids"
echo "Terminating processes..."

for pid in $pid; do
  kill -9 $pid
  echo "Terminated process with PID $pid"
done
  • pgrep "$process_name": Finds all PIDs for the given process name.
  • if [ -z "$pids" ]; then ... fi: Checks if any PIDs were found.
  • for pid in $pids; do ... done: Iterates over each PID and sends the SIGKILL signal to terminate it.
posted @ 2024-05-24 03:11  Zhentiw  阅读(6)  评论(0编辑  收藏  举报