2

I can kill a detached screen session with this command:

sudo kill $(screen -ls | awk '/ScreenName/ { print $1 }' | cut -f 1 -d '.')

I am trying to implement this to a simple PHP page:

<?php
if ($_GET['run']) {
        $cmd =shell_exec("screen -ls | awk '/ScreenName/ { print $1 }' | cut -f 1 -d '.'");
        system('sudo kill $cmd');
?>
<a href="?run=true">Kill The Screen</a>

However, PHP doesn't work. I think it happens because I can't implement $cmd right.Because, when I try to assign the command to $cmd in terminal and execute it, It doesn't work. In short this happens:

~$ cmd="screen -ls | awk '/ScreenName/ { print $1 }' | cut -f 1 -d '.'"
~$ echo $cmd
screen -ls | awk '/ScreenName/ { print $1}' | cut -f 1 -d '.'
~$ $cmd
No Sockets found in /run/screen/S-ubuntu

~$ screen -ls | awk '/ScreenName/ { print $1}' | cut -f 1 -d '.'
28578

Is it the \ escape character? What could be the problem? Is it the apache user running the screen?

Ekin Karadağ
  • 51
  • 1
  • 7
  • 1
    Can you echo out what $cmd is? Might help you establish what $cmd is actually evaluating as. Also, what user is your PHP script running under? – Andy Macdonald Feb 03 '19 at 10:25
  • It seems to be working for me?... The `\ ` is most likely not the problem since without out it, it will try to find `$1` – Ed The ''Pro'' Feb 03 '19 at 10:27
  • This might help: [screen -X -S ScreenName quit](https://stackoverflow.com/a/1509764/3776858) – Cyrus Feb 03 '19 at 10:52
  • I seems that PHP is running as `www-data`.Could that be the issue? – Ekin Karadağ Feb 03 '19 at 10:55
  • I don't think your original command with `awk '{print \$1}'` works with the escaped `$`. Since it's single quoted, it'll be handed as a literal `\$1` to awk, and awk will choke. – Benjamin W. Feb 03 '19 at 19:00

1 Answers1

0

Use two backslashes.

In PHP \\ is changed to \.

<?php
if ($_GET['run']) {
        $cmd =shell_exec("screen -ls | awk '/ScreenName/ { print \\$1 }' | cut -f 1 -d '.'");
        system('sudo kill $cmd');
?>
<a href="?run=true">Kill The Screen</a>
jiwopene
  • 3,077
  • 17
  • 30