'Unable to get the cpu and memory usage using process id

I am trying to get the process id in PID and then get the cpu and memory usage with all the process id that the grep command has listed but I am facing an error. Any help would be appreciated

#!/bin/bash
PID=`ps -eaf | grep firefox | grep -v grep | awk '{print $2}'`
usage= `ps -p $PID -o %cpu,%mem`

error:

error: process ID list syntax error

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).


Solution 1:[1]

This typically happens when firefox is not running: the PID does not exist and you get following behaviour:

Prompt>ps -p -o %cpu,%mem // as firefox does not run, $PID is empty
error: process ID list syntax error

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).

Solution 2:[2]

The suggested command to get csv list of pid pgrep -d, -f firefox .

Or collect pids_list into variable:

pid_list=$(pgrep -d, -f firefox)

Now use ps command to extract information about $pid_list

ps -p $pid_list -o %cpu,%mem

Or in one line:

ps -p $(pgrep -d, -f firefox) %cpu,%mem

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dominique
Solution 2 Dudi Boy