Home > front end >  Syntax error while trying to get CPU Usage
Syntax error while trying to get CPU Usage

Time:01-28

I would like to get CPU usage using shell_exec but i'm getting syntax error, this is my code:

$cpu_usage = " top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}' ";
shell_exec($cpu_usage);

Error :

syntax error, unexpected 's' (T_STRING)

CodePudding user response:

You're getting this error message because you (unintentionally) terminate the string too early:

$cpu_usage = " top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}' ";
//                             ^ PHP sees this as the end of the string

The most painless way of solving this would be to use nowdoc string notation, as it doesn't do any parsing inside the string:

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.

(emphasis mine)

$cpu_usage = <<<'STR'
top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}'
STR;

shell_exec($cpu_usage);
  •  Tags:  
  • Related