Skip to content

Instantly share code, notes, and snippets.

@1d10t
Created December 19, 2016 16:02
Show Gist options
  • Save 1d10t/4f0420b51a22c1babb714b0e5c506157 to your computer and use it in GitHub Desktop.
Save 1d10t/4f0420b51a22c1babb714b0e5c506157 to your computer and use it in GitHub Desktop.
screen tool: list, attach, reattach
#!/usr/bin/php
<?php
error_reporting(E_ALL);
function scr_ls(){
ob_start();
passthru('screen -ls');
$ss = explode("\n", ob_get_clean());
$scrs = array();
foreach($ss as $s)
if(count($s = explode("\t", rtrim($s))) == 3){
list($pid, $name) = explode('.', $s[1], 2);
$scrs[] = array(
'caption' => "{$s[1]}\t{$s[2]}",
'attached' => $s[2]!='(Detached)',
'dead' => $s[2]=='(Dead ???)',
'name' => $name,
'pid' => $pid,
'fullname' => $s[1],
);
}
return $scrs;
}
function print_scrs($scrs){
foreach($scrs as $i => $s){
echo "$i)\t{$s['caption']}\r\n";
}
}
function attach_screen($scr){
echo "Attaching screen '{$scr['fullname']}'\r\n";
//sleep(4);
passthru('screen -'.($scr['attached']?'x':'r').' '.escapeshellarg($scr['fullname']));
}
function new_screen($name = ''){
echo "Creating new screen", ($name!==false?" with name '$name'":''), "\r\n";
//sleep(4);
passthru('screen'.($name!==false ? ' -S '.escapeshellarg($name) : ''));
}
function mygets(){
return rtrim(fgets(STDIN));
}
function welcome($scrs){
echo "Select screen by nubmer (or by fullname,pid,name) or enter 'n <name>' to create new\r\n";
print_scrs($scrs);
echo ": ";
}
function get_newname($s){
$s = preg_split('#\s+#', $s, 2, PREG_SPLIT_NO_EMPTY);
return $s[0] == 'n'
? (isset($s[1]) ? $s[1] : '')
: false
;
}
function search_screen($scrs, $search){
foreach($scrs as $i => $s)
if(!$s['dead'])
if((string)$i == $search
|| $s['fullname'] == $search
|| $s['pid'] == $search
|| strpos($s['name'], $search) === 0)
return $s;
return false;
}
////////////////////////////////////////////
$name = isset($GLOBALS['argv'][1]) ? $GLOBALS['argv'][1] : '';
do{
$scrs = scr_ls();
//print_r( $scrs );
if($name === ''){
welcome($scrs);
$s = mygets();
if(($scr = search_screen($scrs, $s)) !== false){
attach_screen($scr);
break;
}elseif(($n = get_newname($s)) !== false){
new_screen($n);
break;
}
}elseif(($scr = search_screen($scrs, $name)) !== false){
attach_screen($scr);
break;
}else
$name = '';
}while(1);
echo "'scr' tool\r\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment