Process Commands in Shell Scripting
Command Explanation Syntax Example
ps Displays currently running ps ps → Shows active
processes along with their PID processes.
(Process ID), terminal, and
CPU usage.
ps aux Shows all system processes with ps aux ps aux → Lists all
detailed information. running processes.
top Displays real-time CPU & top top → Monitors system
memory usage of processes. resource usage.
kill Terminates a process using its kill PID kill 1234 → Stops
PID. process with PID 1234.
kill -9 Forcefully kills a process kill -9 PID kill -9 5678 →
(SIGKILL). Forcefully kills PID 5678.
pkill Kills a process using its name pkill pkill firefox → Kills
instead of PID. process_name all firefox processes.
bg Resumes a stopped process and bg Press Ctrl + Z, then type
runs it in the background. bg to continue the stopped
process.
fg Brings a background process to fg fg %1 → Brings job 1 to
the foreground. the foreground.
nohup Runs a command even after nohup command nohup ./script.sh & →
logging out. & Keeps script.sh running.
jobs Lists all background processes. jobs jobs → Displays
background jobs.
nice Starts a process with a specific nice -n nice -n 10 ./script.sh
priority (lower values = higher priority → Runs script with
command priority 10.
priority).
renice Changes the priority of a renice renice 5 -p 1234 →
running process. priority -p Changes priority of PID
PID
1234 to 5.
How to Use Process Commands in a Script?
Here’s a simple script that demonstrates the use of process commands:
#!/bin/bash
# Running a process in the background
sleep 100 &
echo "Process started in background with PID: $!"
# Listing active processes
echo "Active processes:"
ps
# Monitoring CPU & memory usage
echo "Displaying top processes:"
top -n 1
# Killing the background process
kill $!
echo "Process $! has been terminated."
Key Takeaways
• Process Management is essential to control system resources efficiently.
• Use ps, top, and jobs to view running processes.
• Use kill and pkill to terminate processes.
• Use bg and fg to manage background and foreground jobs.
• Use nice and renice to set process priority.