0

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)

Marco
  • 7,007
  • 2
  • 19
  • 49
  • Can you print out the contents of `$cpu_usage` after you set it? Also, what exactly is the error you receive? – John Glenn Jan 28 '22 at 01:50
  • @JohnGlenn updated please double check :) –  Jan 28 '22 at 01:51
  • Does this answer your question? [PHP parse/syntax errors; and how to solve them](https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them) – Marco Jan 28 '22 at 01:51
  • You need to escape certain characters in your command -- `" top -bn1 | grep "Cpu(s)"` for example should be `" top -bn1 | grep \"Cpu(s)\" ` – Marco Jan 28 '22 at 01:52
  • @marco-a yes exactly, which one :) ? –  Jan 28 '22 at 01:55
  • @ElYousfiRachid I'd use a nowdoc string here, see my answer. – Marco Jan 28 '22 at 02:04

1 Answers1

0

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);
Marco
  • 7,007
  • 2
  • 19
  • 49