0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Kill a Process in Bash: Simple Commands Explained

To kill a process in bash, use the kill command followed by the process ID (PID), like kill 1234. You can also use pkill with the process name, for example pkill firefox, to stop processes by name.
📐

Syntax

The kill command sends signals to processes. The basic syntax is:

  • kill [signal] PID - sends a signal to a process by its ID.
  • pkill [signal] process_name - sends a signal to processes by name.

Common signals include SIGTERM (default, politely asks process to stop) and SIGKILL (forces process to stop immediately).

bash
kill [signal] PID
pkill [signal] process_name
💻

Example

This example shows how to find a process ID and kill it politely, then force kill if needed.

bash
# Find the PID of a process named 'sleep'
pid=$(pgrep sleep)

# Kill the process politely
kill $pid

# If still running, force kill
kill -9 $pid
⚠️

Common Pitfalls

Common mistakes include:

  • Using kill without the correct PID.
  • Not having permission to kill a process (may need sudo).
  • Using kill -9 too often, which doesn't allow cleanup.

Always try kill without -9 first to allow graceful shutdown.

bash
# Wrong: killing without PID
kill

# Right: specify PID
kill 1234
Output
bash: kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
📊

Quick Reference

CommandDescription
kill PIDSend SIGTERM to process with PID
kill -9 PIDSend SIGKILL to force kill process
pkill process_nameKill process by name with SIGTERM
pkill -9 process_nameForce kill process by name
pgrep process_nameFind PID(s) of process by name

Key Takeaways

Use kill PID to politely stop a process by its ID.
Use pkill process_name to kill processes by name.
Try to avoid kill -9 unless necessary to force stop.
You may need sudo if you lack permission to kill a process.
Find process IDs with pgrep before killing.