Question

I have a shell script that is supposed to kill a detached screen session if it exists. The script is

if ! screen -list | grep -q "ScreenName"; then
  screen -S ScreenName -X quit
fi

Unfortunately it seems that the screen -S ... -X quit command always runs bc when I run the script and the screen session doesn't exist it still outputs "No screen sessions found." When I remove the ! and the screen session is running, it doesn't kill the running session.

What could the problem be? Thanks

Was it helpful?

Solution 2

grep has a confusing convention for return codes. It returns 0 when a string is found and returns 1 when there is no match. You should omit the ! in the condition.

OTHER TIPS

To get rid of the "No screen sessions found" message, redirect the stderr of screen:

screen -list 2>/dev/null

Next, keep in mind that -X doesn't work if the session is password protected.

Then, use -r to let screen know you only want to kill detached sessions, and there's no more need for grep and if.

Putting it all together:

screen -r -S "ScreenName" -X quit 2>/dev/null

@Sir Athos answer is pretty good, if you don't want to ignore valid errors, or just want additional ways to do things in the future, you can use this as a reference:

screen -ls 2>&1 | grep '(Detached)' | grep -o 'ScreenName' | xargs -I{} -n 1 -r screen -r -S {} -X quit
  1. screen -ls 2>&1 List sessions, all output to stdout
  2. grep '(Detached)' Filter for detached sessions
  3. grep -o 'ScreenName' Filter for ScreenName and only output ScreenName
  4. xargs -I{} -n 1 -r screen -r -S {} -X quit Run output through xargs -n 1 one at a time, -r don't run if there is no output, -I{} use {} as the replacement location for your argument since it's not at the end, and run your command

Code Sample:

evan> screen -ls  
There are screens on:  
        15491.pts-2.x      (08/29/2013 10:43:53 AM)        (Detached)  
        31676.pts-41.x     (08/28/2013 10:55:00 AM)        (Attached)  
2 Sockets in /var/run/screen/S-evan.  

evan> screen -ls 2>&1 | grep '(Detached)' | grep -o '15491.pts-2.x' | xargs -I{} -n 1 -r screen -r -S {} -X quit  

evan> screen -ls  
There is a screen on:  
        31676.pts-41.x     (08/28/2013 10:55:00 AM)        (Attached)  
1 Socket in /var/run/screen/S-evan.  

evan> screen -ls 2>&1 | grep '(Detached)' | grep -o '15491.pts-2.x' | xargs -I{} -n 1 -r screen -r -S {} -X quit

evan>  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top