The ps command in shell scripts is used to view details of processes currently running on the system. This command is highly useful as it helps us identify which programs are executing, their process IDs (PID), the user accounts under which they run, and their status.
For example, if I am developing a service and need to ensure it runs continuously, I can use the ps command to check if my service process is listed in the process list. This way, I can promptly detect and restart the service if it unexpectedly stops.
The command format is typically as follows:
bashps aux
Here, a indicates displaying processes for all users, u indicates displaying in a user-friendly format, and x indicates displaying processes without a controlling terminal.
This command lists all processes in the system, including process IDs, CPU usage, memory usage, virtual memory usage, and elapsed time. With this information, we can gain a comprehensive understanding of the system's operational status and perform corresponding management and optimization.
For instance, if I need to identify the process with the highest CPU usage, I can use the ps command combined with the sort command as follows:
bashps aux | sort -nrk 3,3 | head
This command sorts the process list by CPU usage in descending order and displays the top few processes with the highest usage. This is particularly helpful for performance tuning and troubleshooting.