function::pid - Linux


The pid function is a Shell Built-in command that converts a given number or variable to an integer, ensuring it represents a valid process ID (PID). It is commonly utilized to validate and work with PIDs in scripts or command pipelines.


pid [-s] [-w] <number-or-variable>


  • -s: Prevent errors by returning an empty string on invalid PIDs (default behavior).
  • -w: Consider any integer argument as a PID (even those outside the valid range).


  • Check if a PID is valid:
if pid 1234; then
  echo "Valid PID"
  echo "Invalid PID"
  • Convert a variable to an integer PID:
pid $pid_str
  • Parse a PID from a command’s output:
pid=$(ps -ef | grep my_process | awk '{print $2}')

Common Issues

  • Out-of-range PIDs: By default, pid detects PIDs outside the valid range (0-32768). Use -w for more flexibility.
  • Empty string result: If -s is not used, an invalid PID will result in an error.


pid can be used in conjunction with other commands to:

  • Validate PIDs before sending signals: if pid $pid; then kill -9 $pid; fi
  • Extract PIDs from process listings: ps -ef | grep my_process | awk '{print pid $2}'
  • Create scripts that interact with running processes: Combine pid with pgrep, pkill, and other process-related commands.

Related Commands

  • kill: Send signals to processes based on PID.
  • ps: List running processes and their PIDs.
  • pgrep: Find processes based on name or pattern.