I'm trying to do this: if a GNU screen named worker already exists, then reattach to it, else create it by starting python example.py.

I tried:

if [ls /var/run/screen/S-root/ |grep -Fxq worker] then screen -r worker else cd /home/www/example/; screen -S worker python example.py fi

but it doesn't seem to work.

Is there something wrong in the syntax?

  • What do you mean by this screen -S worker python example.py, you want to create a session and run python example.py in it ? – Bharat Apr 18 '18 at 20:19
  • @Bharat yes, if the session is not already running and detached. – Basj Apr 18 '18 at 20:20

It makes more sense to use screen -ls or

screen -S worker -x || { cd /home/www/example; screen -S worker python example.py; }

But the errors in your code are

  1. the unnecessary [ (which would have needed spaces around it)

    if [ls /var/run/screen/S-root/ |grep -Fxq worker]

    must be

    if ls /var/run/screen/S-root/ | grep -Fxq worker
  2. the missing ; / newline before then

    |grep -Fxq worker] then

    must be

    | grep -Fxq worker; then
  3. the missing ; / newline before else

     then screen -r worker else

    must be

     then screen -r worker; else
  4. the missing ; / newline before fi

    python example.py fi

    must be

    python example.py; fi
  • Thanks a lot, your solution screen -S worker -x || { ... } works fine. And I learnt about the missing ; + unncessary [, thanks as well! – Basj Apr 18 '18 at 20:37
  • 1
    @Basj I use that every day because I start screen as root with the config file of my normal user account. – Hauke Laging Apr 18 '18 at 20:41
  • Also my -Fxq was wrong. if screen -ls |grep -Fq worker; then screen -r worker; else cd /home/www/example/; screen -S worker python example.py; fi is correct. – Basj Apr 18 '18 at 20:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.