automatically start screen upon ssh login The 2019 Stack Overflow Developer Survey Results Are...

Word for: a synonym with a positive connotation?

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

What's the point in a preamp?

Do I have Disadvantage attacking with an off-hand weapon?

Circular reasoning in L'Hopital's rule

Does Parliament hold absolute power in the UK?

Can the DM override racial traits?

One-dimensional Japanese puzzle

Can I visit the Trinity College (Cambridge) library and see some of their rare books

Is it ethical to upload a automatically generated paper to a non peer-reviewed site as part of a larger research?

What do I do when my TA workload is more than expected?

What happens to a Warlock's expended Spell Slots when they gain a Level?

Windows 10: How to Lock (not sleep) laptop on lid close?

Can withdrawing asylum be illegal?

Using dividends to reduce short term capital gains?

Intergalactic human space ship encounters another ship, character gets shunted off beyond known universe, reality starts collapsing

Is there a writing software that you can sort scenes like slides in PowerPoint?

Solving overdetermined system by QR decomposition

Variable with quotation marks "$()"

Why can't devices on different VLANs, but on the same subnet, communicate?

Simulating Exploding Dice

Sub-subscripts in strings cause different spacings than subscripts

Is an up-to-date browser secure on an out-of-date OS?

"... to apply for a visa" or "... and applied for a visa"?



automatically start screen upon ssh login



The 2019 Stack Overflow Developer Survey Results Are In
Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manarassh-agent and screenCan't start GNU screen on Snow Leopardstart gnu screen automaticallyHow do detatch and reattach a x-forwarded ssh-session?Reopen screen session after connecting to serverReattaching screen (having irssi running) forces window resizeRestart a process in detached screen via sshAfter logging out of SSH, screen sessions disappear on Arch Linuxssh, screen, run command and detach in one go?Putty closes on detach screen





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







14















I have been reading about how to automatically start a screen when I ssh to a remote server. I would like a simple one-liner to add to my .bash_profile to start screen when I ssh in, and NOT exit my remote connection when I detach the screen.



I have been looking into exec screen and pretty much every combination of -d, -r, -D and -R and cannot figure out what flags I need.



Ideally I would type ssh whatever and be logged into the server in a new screen or it can reattach an old screen, I would kind of like to know how to do both to see which I like better. Then I can either type Ctrl ad or Ctrl d and have it bring me back to the normal ssh login for that server (where you would see the motd). From there I can screen -r back into whatever screen I want, or hit Ctrl d again to log out.










share|improve this question















migrated from stackoverflow.com Apr 9 '13 at 1:55


This question came from our site for professional and enthusiast programmers.

























    14















    I have been reading about how to automatically start a screen when I ssh to a remote server. I would like a simple one-liner to add to my .bash_profile to start screen when I ssh in, and NOT exit my remote connection when I detach the screen.



    I have been looking into exec screen and pretty much every combination of -d, -r, -D and -R and cannot figure out what flags I need.



    Ideally I would type ssh whatever and be logged into the server in a new screen or it can reattach an old screen, I would kind of like to know how to do both to see which I like better. Then I can either type Ctrl ad or Ctrl d and have it bring me back to the normal ssh login for that server (where you would see the motd). From there I can screen -r back into whatever screen I want, or hit Ctrl d again to log out.










    share|improve this question















    migrated from stackoverflow.com Apr 9 '13 at 1:55


    This question came from our site for professional and enthusiast programmers.





















      14












      14








      14


      7






      I have been reading about how to automatically start a screen when I ssh to a remote server. I would like a simple one-liner to add to my .bash_profile to start screen when I ssh in, and NOT exit my remote connection when I detach the screen.



      I have been looking into exec screen and pretty much every combination of -d, -r, -D and -R and cannot figure out what flags I need.



      Ideally I would type ssh whatever and be logged into the server in a new screen or it can reattach an old screen, I would kind of like to know how to do both to see which I like better. Then I can either type Ctrl ad or Ctrl d and have it bring me back to the normal ssh login for that server (where you would see the motd). From there I can screen -r back into whatever screen I want, or hit Ctrl d again to log out.










      share|improve this question
















      I have been reading about how to automatically start a screen when I ssh to a remote server. I would like a simple one-liner to add to my .bash_profile to start screen when I ssh in, and NOT exit my remote connection when I detach the screen.



      I have been looking into exec screen and pretty much every combination of -d, -r, -D and -R and cannot figure out what flags I need.



      Ideally I would type ssh whatever and be logged into the server in a new screen or it can reattach an old screen, I would kind of like to know how to do both to see which I like better. Then I can either type Ctrl ad or Ctrl d and have it bring me back to the normal ssh login for that server (where you would see the motd). From there I can screen -r back into whatever screen I want, or hit Ctrl d again to log out.







      linux ssh gnu-screen






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 22 '15 at 19:58









      Karl Richter

      94231640




      94231640










      asked Apr 9 '13 at 1:14









      Ronald DreganRonald Dregan

      73114




      73114




      migrated from stackoverflow.com Apr 9 '13 at 1:55


      This question came from our site for professional and enthusiast programmers.









      migrated from stackoverflow.com Apr 9 '13 at 1:55


      This question came from our site for professional and enthusiast programmers.
























          6 Answers
          6






          active

          oldest

          votes


















          18














          A simple screen -R should do the trick.



          To verify this, I added screen -R to my .bash_profile on a remote server, logged in, detached from screen, and was dropped back to a normal shell prompt on the remote server. Verified with .bashrc as well. Subsequent logins yielded the expected result (re-attach to screen session).






          share|improve this answer
























          • Thanks! I was reading around and I was under the impression that I would need exec screen -R. Glad this worked

            – Ronald Dregan
            Apr 9 '13 at 3:48













          • Is it a bad idea to put logout or exit right after that line s.t. an ssh session is immediately terminated once the screen is closed by ctrl+D?

            – Griddo
            Jan 4 '17 at 12:49











          • This did not work for me. I started a few dozen screens since the line is executed every time a session starts. How did you do it so that this does not happen?

            – Thomas
            Jun 26 '18 at 9:04





















          9














          I had issues with 40 cascading screen sessions being created with some of the solutions when starting a new window or screen session. I was able to eliminate the cascading screen and create a new session if one didn't exist with this:



          if [ -z "$STY" ]; then screen -R; fi


          It tests whether you're in a screen session and runs screen -R if you aren't. Without the test you get the "Attaching from inside of screen?" warning from screen each time you create a new screen window.






          share|improve this answer
























          • +1 - like this better than the screen -ls test that Tony mentioned

            – cwd
            Mar 22 '16 at 20:53



















          8














          If I understand your need, you should try :



          if $(screen -ls | grep -q pts); then screen -x; else screen -R; fi



          It will create only one screen session, otherwise it will reconnect to the existing one in a multi-windows fashion ( even if you have multiple ssh session, you will end up to the same screen session )






          share|improve this answer


























          • I like this idea for its recognition that we have multi-window SSH clients (or sometimes go and log in directly on the machine). It's quite flexible if you use something like Bitvise and have multiple terminal windows open - you can turn individual screen windows into separate physical windows.

            – Piku
            Oct 16 '16 at 20:57











          • All this can be replaced with screen -xR, which seems to be parsed as "attach if there's something to attach to, else make new screen".

            – Piskvor
            Jan 3 at 14:44



















          7














          screen -RR will reattach to the first available session or create one if necessary.






          share|improve this answer


























          • that was really useful as using screen -R was causing me trouble with multiple sessions.

            – David V.
            Sep 28 '16 at 9:09











          • This is awesome, thanks! It connects to the first "Detached" session found (if there are any), and ignores attached sessions. So it allows you to login and have multiple windows open, but still make sure that each session has the protection of running in a screen. Our OPS people thank you!

            – Ian McGowan
            Dec 2 '16 at 19:36



















          0














          Here a little extension,



          the script for the bashrc check if there is more than one detached screen session. If there is more, then you must choose the session manualy.
          Whene there is a detached session, you come back to this session.
          If you exit the session then the ssh session will close up too.



           #Start Screen
          if [ -z "$STY" ]; then

          value=$( screen -ls |grep '<pts.*Detached>' |wc -l )

          if [ $value -gt 1 ]; then

          screen -ls

          else

          screen -R

          echo 5 Sek. bis die SSH Session beendet wird.

          echo Strg + C - um ohne screen weiter zu arbeiten.

          sleep 6

          exit

          fi

          fi





          share|improve this answer

































            0














            If you want to connect automatically to a screen session when you connect via SSH, add the code below to your .bash_profile or your .bashrc on your remote machine, it will:




            • Start a new screen session every time you connect through SSH.

            • Re-use already existing detached screen session, always starting with the latest one. If no detached sessions available it starts a new one.

            • When you open multiple SSH connections to your machine you will get a different screen session since we are only re-using detached ones.

            • Avoid loops in case you are adding the script to your .bashrc


            Here is the script:



            #!/bin/bash
            #
            # Attaches to the first Detached Screen. Otherwise starts a new Screen.

            # Only run if we are not already inside a running screen and only if in an SSH session.
            if [[ -z "${STY}" && ! -z "${SSH_CLIENT}" ]]; then
            detached_screens=($(screen -ls | grep pts | grep -v Attached))

            for screen in "${detached_screens[@]}"; do
            if [[ "${screen}" == *".pts"* ]]; then
            IFS='.pts' read -ra split <<< "${screen}"
            for id in "${split[@]}"; do
            first_id="${id}"
            break
            done
            break
            fi
            done

            screen -R $first_id
            fi


            PS: If you would like to enable this for local terminal, remove && ! -z "${SSH_CLIENT} on the first line.






            share|improve this answer








            New contributor




            Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.





















              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "3"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f580087%2fautomatically-start-screen-upon-ssh-login%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              6 Answers
              6






              active

              oldest

              votes








              6 Answers
              6






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              18














              A simple screen -R should do the trick.



              To verify this, I added screen -R to my .bash_profile on a remote server, logged in, detached from screen, and was dropped back to a normal shell prompt on the remote server. Verified with .bashrc as well. Subsequent logins yielded the expected result (re-attach to screen session).






              share|improve this answer
























              • Thanks! I was reading around and I was under the impression that I would need exec screen -R. Glad this worked

                – Ronald Dregan
                Apr 9 '13 at 3:48













              • Is it a bad idea to put logout or exit right after that line s.t. an ssh session is immediately terminated once the screen is closed by ctrl+D?

                – Griddo
                Jan 4 '17 at 12:49











              • This did not work for me. I started a few dozen screens since the line is executed every time a session starts. How did you do it so that this does not happen?

                – Thomas
                Jun 26 '18 at 9:04


















              18














              A simple screen -R should do the trick.



              To verify this, I added screen -R to my .bash_profile on a remote server, logged in, detached from screen, and was dropped back to a normal shell prompt on the remote server. Verified with .bashrc as well. Subsequent logins yielded the expected result (re-attach to screen session).






              share|improve this answer
























              • Thanks! I was reading around and I was under the impression that I would need exec screen -R. Glad this worked

                – Ronald Dregan
                Apr 9 '13 at 3:48













              • Is it a bad idea to put logout or exit right after that line s.t. an ssh session is immediately terminated once the screen is closed by ctrl+D?

                – Griddo
                Jan 4 '17 at 12:49











              • This did not work for me. I started a few dozen screens since the line is executed every time a session starts. How did you do it so that this does not happen?

                – Thomas
                Jun 26 '18 at 9:04
















              18












              18








              18







              A simple screen -R should do the trick.



              To verify this, I added screen -R to my .bash_profile on a remote server, logged in, detached from screen, and was dropped back to a normal shell prompt on the remote server. Verified with .bashrc as well. Subsequent logins yielded the expected result (re-attach to screen session).






              share|improve this answer













              A simple screen -R should do the trick.



              To verify this, I added screen -R to my .bash_profile on a remote server, logged in, detached from screen, and was dropped back to a normal shell prompt on the remote server. Verified with .bashrc as well. Subsequent logins yielded the expected result (re-attach to screen session).







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 9 '13 at 2:34









              btanakabtanaka

              29623




              29623













              • Thanks! I was reading around and I was under the impression that I would need exec screen -R. Glad this worked

                – Ronald Dregan
                Apr 9 '13 at 3:48













              • Is it a bad idea to put logout or exit right after that line s.t. an ssh session is immediately terminated once the screen is closed by ctrl+D?

                – Griddo
                Jan 4 '17 at 12:49











              • This did not work for me. I started a few dozen screens since the line is executed every time a session starts. How did you do it so that this does not happen?

                – Thomas
                Jun 26 '18 at 9:04





















              • Thanks! I was reading around and I was under the impression that I would need exec screen -R. Glad this worked

                – Ronald Dregan
                Apr 9 '13 at 3:48













              • Is it a bad idea to put logout or exit right after that line s.t. an ssh session is immediately terminated once the screen is closed by ctrl+D?

                – Griddo
                Jan 4 '17 at 12:49











              • This did not work for me. I started a few dozen screens since the line is executed every time a session starts. How did you do it so that this does not happen?

                – Thomas
                Jun 26 '18 at 9:04



















              Thanks! I was reading around and I was under the impression that I would need exec screen -R. Glad this worked

              – Ronald Dregan
              Apr 9 '13 at 3:48







              Thanks! I was reading around and I was under the impression that I would need exec screen -R. Glad this worked

              – Ronald Dregan
              Apr 9 '13 at 3:48















              Is it a bad idea to put logout or exit right after that line s.t. an ssh session is immediately terminated once the screen is closed by ctrl+D?

              – Griddo
              Jan 4 '17 at 12:49





              Is it a bad idea to put logout or exit right after that line s.t. an ssh session is immediately terminated once the screen is closed by ctrl+D?

              – Griddo
              Jan 4 '17 at 12:49













              This did not work for me. I started a few dozen screens since the line is executed every time a session starts. How did you do it so that this does not happen?

              – Thomas
              Jun 26 '18 at 9:04







              This did not work for me. I started a few dozen screens since the line is executed every time a session starts. How did you do it so that this does not happen?

              – Thomas
              Jun 26 '18 at 9:04















              9














              I had issues with 40 cascading screen sessions being created with some of the solutions when starting a new window or screen session. I was able to eliminate the cascading screen and create a new session if one didn't exist with this:



              if [ -z "$STY" ]; then screen -R; fi


              It tests whether you're in a screen session and runs screen -R if you aren't. Without the test you get the "Attaching from inside of screen?" warning from screen each time you create a new screen window.






              share|improve this answer
























              • +1 - like this better than the screen -ls test that Tony mentioned

                – cwd
                Mar 22 '16 at 20:53
















              9














              I had issues with 40 cascading screen sessions being created with some of the solutions when starting a new window or screen session. I was able to eliminate the cascading screen and create a new session if one didn't exist with this:



              if [ -z "$STY" ]; then screen -R; fi


              It tests whether you're in a screen session and runs screen -R if you aren't. Without the test you get the "Attaching from inside of screen?" warning from screen each time you create a new screen window.






              share|improve this answer
























              • +1 - like this better than the screen -ls test that Tony mentioned

                – cwd
                Mar 22 '16 at 20:53














              9












              9








              9







              I had issues with 40 cascading screen sessions being created with some of the solutions when starting a new window or screen session. I was able to eliminate the cascading screen and create a new session if one didn't exist with this:



              if [ -z "$STY" ]; then screen -R; fi


              It tests whether you're in a screen session and runs screen -R if you aren't. Without the test you get the "Attaching from inside of screen?" warning from screen each time you create a new screen window.






              share|improve this answer













              I had issues with 40 cascading screen sessions being created with some of the solutions when starting a new window or screen session. I was able to eliminate the cascading screen and create a new session if one didn't exist with this:



              if [ -z "$STY" ]; then screen -R; fi


              It tests whether you're in a screen session and runs screen -R if you aren't. Without the test you get the "Attaching from inside of screen?" warning from screen each time you create a new screen window.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 5 '15 at 18:12









              seq3seq3

              9112




              9112













              • +1 - like this better than the screen -ls test that Tony mentioned

                – cwd
                Mar 22 '16 at 20:53



















              • +1 - like this better than the screen -ls test that Tony mentioned

                – cwd
                Mar 22 '16 at 20:53

















              +1 - like this better than the screen -ls test that Tony mentioned

              – cwd
              Mar 22 '16 at 20:53





              +1 - like this better than the screen -ls test that Tony mentioned

              – cwd
              Mar 22 '16 at 20:53











              8














              If I understand your need, you should try :



              if $(screen -ls | grep -q pts); then screen -x; else screen -R; fi



              It will create only one screen session, otherwise it will reconnect to the existing one in a multi-windows fashion ( even if you have multiple ssh session, you will end up to the same screen session )






              share|improve this answer


























              • I like this idea for its recognition that we have multi-window SSH clients (or sometimes go and log in directly on the machine). It's quite flexible if you use something like Bitvise and have multiple terminal windows open - you can turn individual screen windows into separate physical windows.

                – Piku
                Oct 16 '16 at 20:57











              • All this can be replaced with screen -xR, which seems to be parsed as "attach if there's something to attach to, else make new screen".

                – Piskvor
                Jan 3 at 14:44
















              8














              If I understand your need, you should try :



              if $(screen -ls | grep -q pts); then screen -x; else screen -R; fi



              It will create only one screen session, otherwise it will reconnect to the existing one in a multi-windows fashion ( even if you have multiple ssh session, you will end up to the same screen session )






              share|improve this answer


























              • I like this idea for its recognition that we have multi-window SSH clients (or sometimes go and log in directly on the machine). It's quite flexible if you use something like Bitvise and have multiple terminal windows open - you can turn individual screen windows into separate physical windows.

                – Piku
                Oct 16 '16 at 20:57











              • All this can be replaced with screen -xR, which seems to be parsed as "attach if there's something to attach to, else make new screen".

                – Piskvor
                Jan 3 at 14:44














              8












              8








              8







              If I understand your need, you should try :



              if $(screen -ls | grep -q pts); then screen -x; else screen -R; fi



              It will create only one screen session, otherwise it will reconnect to the existing one in a multi-windows fashion ( even if you have multiple ssh session, you will end up to the same screen session )






              share|improve this answer















              If I understand your need, you should try :



              if $(screen -ls | grep -q pts); then screen -x; else screen -R; fi



              It will create only one screen session, otherwise it will reconnect to the existing one in a multi-windows fashion ( even if you have multiple ssh session, you will end up to the same screen session )







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 9 '13 at 2:50

























              answered Apr 9 '13 at 2:39









              TonyTony

              21615




              21615













              • I like this idea for its recognition that we have multi-window SSH clients (or sometimes go and log in directly on the machine). It's quite flexible if you use something like Bitvise and have multiple terminal windows open - you can turn individual screen windows into separate physical windows.

                – Piku
                Oct 16 '16 at 20:57











              • All this can be replaced with screen -xR, which seems to be parsed as "attach if there's something to attach to, else make new screen".

                – Piskvor
                Jan 3 at 14:44



















              • I like this idea for its recognition that we have multi-window SSH clients (or sometimes go and log in directly on the machine). It's quite flexible if you use something like Bitvise and have multiple terminal windows open - you can turn individual screen windows into separate physical windows.

                – Piku
                Oct 16 '16 at 20:57











              • All this can be replaced with screen -xR, which seems to be parsed as "attach if there's something to attach to, else make new screen".

                – Piskvor
                Jan 3 at 14:44

















              I like this idea for its recognition that we have multi-window SSH clients (or sometimes go and log in directly on the machine). It's quite flexible if you use something like Bitvise and have multiple terminal windows open - you can turn individual screen windows into separate physical windows.

              – Piku
              Oct 16 '16 at 20:57





              I like this idea for its recognition that we have multi-window SSH clients (or sometimes go and log in directly on the machine). It's quite flexible if you use something like Bitvise and have multiple terminal windows open - you can turn individual screen windows into separate physical windows.

              – Piku
              Oct 16 '16 at 20:57













              All this can be replaced with screen -xR, which seems to be parsed as "attach if there's something to attach to, else make new screen".

              – Piskvor
              Jan 3 at 14:44





              All this can be replaced with screen -xR, which seems to be parsed as "attach if there's something to attach to, else make new screen".

              – Piskvor
              Jan 3 at 14:44











              7














              screen -RR will reattach to the first available session or create one if necessary.






              share|improve this answer


























              • that was really useful as using screen -R was causing me trouble with multiple sessions.

                – David V.
                Sep 28 '16 at 9:09











              • This is awesome, thanks! It connects to the first "Detached" session found (if there are any), and ignores attached sessions. So it allows you to login and have multiple windows open, but still make sure that each session has the protection of running in a screen. Our OPS people thank you!

                – Ian McGowan
                Dec 2 '16 at 19:36
















              7














              screen -RR will reattach to the first available session or create one if necessary.






              share|improve this answer


























              • that was really useful as using screen -R was causing me trouble with multiple sessions.

                – David V.
                Sep 28 '16 at 9:09











              • This is awesome, thanks! It connects to the first "Detached" session found (if there are any), and ignores attached sessions. So it allows you to login and have multiple windows open, but still make sure that each session has the protection of running in a screen. Our OPS people thank you!

                – Ian McGowan
                Dec 2 '16 at 19:36














              7












              7








              7







              screen -RR will reattach to the first available session or create one if necessary.






              share|improve this answer















              screen -RR will reattach to the first available session or create one if necessary.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 18 '14 at 21:02









              Excellll

              11.2k74164




              11.2k74164










              answered Sep 18 '14 at 20:53









              user1187902user1187902

              7111




              7111













              • that was really useful as using screen -R was causing me trouble with multiple sessions.

                – David V.
                Sep 28 '16 at 9:09











              • This is awesome, thanks! It connects to the first "Detached" session found (if there are any), and ignores attached sessions. So it allows you to login and have multiple windows open, but still make sure that each session has the protection of running in a screen. Our OPS people thank you!

                – Ian McGowan
                Dec 2 '16 at 19:36



















              • that was really useful as using screen -R was causing me trouble with multiple sessions.

                – David V.
                Sep 28 '16 at 9:09











              • This is awesome, thanks! It connects to the first "Detached" session found (if there are any), and ignores attached sessions. So it allows you to login and have multiple windows open, but still make sure that each session has the protection of running in a screen. Our OPS people thank you!

                – Ian McGowan
                Dec 2 '16 at 19:36

















              that was really useful as using screen -R was causing me trouble with multiple sessions.

              – David V.
              Sep 28 '16 at 9:09





              that was really useful as using screen -R was causing me trouble with multiple sessions.

              – David V.
              Sep 28 '16 at 9:09













              This is awesome, thanks! It connects to the first "Detached" session found (if there are any), and ignores attached sessions. So it allows you to login and have multiple windows open, but still make sure that each session has the protection of running in a screen. Our OPS people thank you!

              – Ian McGowan
              Dec 2 '16 at 19:36





              This is awesome, thanks! It connects to the first "Detached" session found (if there are any), and ignores attached sessions. So it allows you to login and have multiple windows open, but still make sure that each session has the protection of running in a screen. Our OPS people thank you!

              – Ian McGowan
              Dec 2 '16 at 19:36











              0














              Here a little extension,



              the script for the bashrc check if there is more than one detached screen session. If there is more, then you must choose the session manualy.
              Whene there is a detached session, you come back to this session.
              If you exit the session then the ssh session will close up too.



               #Start Screen
              if [ -z "$STY" ]; then

              value=$( screen -ls |grep '<pts.*Detached>' |wc -l )

              if [ $value -gt 1 ]; then

              screen -ls

              else

              screen -R

              echo 5 Sek. bis die SSH Session beendet wird.

              echo Strg + C - um ohne screen weiter zu arbeiten.

              sleep 6

              exit

              fi

              fi





              share|improve this answer






























                0














                Here a little extension,



                the script for the bashrc check if there is more than one detached screen session. If there is more, then you must choose the session manualy.
                Whene there is a detached session, you come back to this session.
                If you exit the session then the ssh session will close up too.



                 #Start Screen
                if [ -z "$STY" ]; then

                value=$( screen -ls |grep '<pts.*Detached>' |wc -l )

                if [ $value -gt 1 ]; then

                screen -ls

                else

                screen -R

                echo 5 Sek. bis die SSH Session beendet wird.

                echo Strg + C - um ohne screen weiter zu arbeiten.

                sleep 6

                exit

                fi

                fi





                share|improve this answer




























                  0












                  0








                  0







                  Here a little extension,



                  the script for the bashrc check if there is more than one detached screen session. If there is more, then you must choose the session manualy.
                  Whene there is a detached session, you come back to this session.
                  If you exit the session then the ssh session will close up too.



                   #Start Screen
                  if [ -z "$STY" ]; then

                  value=$( screen -ls |grep '<pts.*Detached>' |wc -l )

                  if [ $value -gt 1 ]; then

                  screen -ls

                  else

                  screen -R

                  echo 5 Sek. bis die SSH Session beendet wird.

                  echo Strg + C - um ohne screen weiter zu arbeiten.

                  sleep 6

                  exit

                  fi

                  fi





                  share|improve this answer















                  Here a little extension,



                  the script for the bashrc check if there is more than one detached screen session. If there is more, then you must choose the session manualy.
                  Whene there is a detached session, you come back to this session.
                  If you exit the session then the ssh session will close up too.



                   #Start Screen
                  if [ -z "$STY" ]; then

                  value=$( screen -ls |grep '<pts.*Detached>' |wc -l )

                  if [ $value -gt 1 ]; then

                  screen -ls

                  else

                  screen -R

                  echo 5 Sek. bis die SSH Session beendet wird.

                  echo Strg + C - um ohne screen weiter zu arbeiten.

                  sleep 6

                  exit

                  fi

                  fi






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 25 '18 at 7:47









                  bertieb

                  5,672112542




                  5,672112542










                  answered Mar 25 '18 at 7:27









                  ThomasThomas

                  1




                  1























                      0














                      If you want to connect automatically to a screen session when you connect via SSH, add the code below to your .bash_profile or your .bashrc on your remote machine, it will:




                      • Start a new screen session every time you connect through SSH.

                      • Re-use already existing detached screen session, always starting with the latest one. If no detached sessions available it starts a new one.

                      • When you open multiple SSH connections to your machine you will get a different screen session since we are only re-using detached ones.

                      • Avoid loops in case you are adding the script to your .bashrc


                      Here is the script:



                      #!/bin/bash
                      #
                      # Attaches to the first Detached Screen. Otherwise starts a new Screen.

                      # Only run if we are not already inside a running screen and only if in an SSH session.
                      if [[ -z "${STY}" && ! -z "${SSH_CLIENT}" ]]; then
                      detached_screens=($(screen -ls | grep pts | grep -v Attached))

                      for screen in "${detached_screens[@]}"; do
                      if [[ "${screen}" == *".pts"* ]]; then
                      IFS='.pts' read -ra split <<< "${screen}"
                      for id in "${split[@]}"; do
                      first_id="${id}"
                      break
                      done
                      break
                      fi
                      done

                      screen -R $first_id
                      fi


                      PS: If you would like to enable this for local terminal, remove && ! -z "${SSH_CLIENT} on the first line.






                      share|improve this answer








                      New contributor




                      Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.

























                        0














                        If you want to connect automatically to a screen session when you connect via SSH, add the code below to your .bash_profile or your .bashrc on your remote machine, it will:




                        • Start a new screen session every time you connect through SSH.

                        • Re-use already existing detached screen session, always starting with the latest one. If no detached sessions available it starts a new one.

                        • When you open multiple SSH connections to your machine you will get a different screen session since we are only re-using detached ones.

                        • Avoid loops in case you are adding the script to your .bashrc


                        Here is the script:



                        #!/bin/bash
                        #
                        # Attaches to the first Detached Screen. Otherwise starts a new Screen.

                        # Only run if we are not already inside a running screen and only if in an SSH session.
                        if [[ -z "${STY}" && ! -z "${SSH_CLIENT}" ]]; then
                        detached_screens=($(screen -ls | grep pts | grep -v Attached))

                        for screen in "${detached_screens[@]}"; do
                        if [[ "${screen}" == *".pts"* ]]; then
                        IFS='.pts' read -ra split <<< "${screen}"
                        for id in "${split[@]}"; do
                        first_id="${id}"
                        break
                        done
                        break
                        fi
                        done

                        screen -R $first_id
                        fi


                        PS: If you would like to enable this for local terminal, remove && ! -z "${SSH_CLIENT} on the first line.






                        share|improve this answer








                        New contributor




                        Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.























                          0












                          0








                          0







                          If you want to connect automatically to a screen session when you connect via SSH, add the code below to your .bash_profile or your .bashrc on your remote machine, it will:




                          • Start a new screen session every time you connect through SSH.

                          • Re-use already existing detached screen session, always starting with the latest one. If no detached sessions available it starts a new one.

                          • When you open multiple SSH connections to your machine you will get a different screen session since we are only re-using detached ones.

                          • Avoid loops in case you are adding the script to your .bashrc


                          Here is the script:



                          #!/bin/bash
                          #
                          # Attaches to the first Detached Screen. Otherwise starts a new Screen.

                          # Only run if we are not already inside a running screen and only if in an SSH session.
                          if [[ -z "${STY}" && ! -z "${SSH_CLIENT}" ]]; then
                          detached_screens=($(screen -ls | grep pts | grep -v Attached))

                          for screen in "${detached_screens[@]}"; do
                          if [[ "${screen}" == *".pts"* ]]; then
                          IFS='.pts' read -ra split <<< "${screen}"
                          for id in "${split[@]}"; do
                          first_id="${id}"
                          break
                          done
                          break
                          fi
                          done

                          screen -R $first_id
                          fi


                          PS: If you would like to enable this for local terminal, remove && ! -z "${SSH_CLIENT} on the first line.






                          share|improve this answer








                          New contributor




                          Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.










                          If you want to connect automatically to a screen session when you connect via SSH, add the code below to your .bash_profile or your .bashrc on your remote machine, it will:




                          • Start a new screen session every time you connect through SSH.

                          • Re-use already existing detached screen session, always starting with the latest one. If no detached sessions available it starts a new one.

                          • When you open multiple SSH connections to your machine you will get a different screen session since we are only re-using detached ones.

                          • Avoid loops in case you are adding the script to your .bashrc


                          Here is the script:



                          #!/bin/bash
                          #
                          # Attaches to the first Detached Screen. Otherwise starts a new Screen.

                          # Only run if we are not already inside a running screen and only if in an SSH session.
                          if [[ -z "${STY}" && ! -z "${SSH_CLIENT}" ]]; then
                          detached_screens=($(screen -ls | grep pts | grep -v Attached))

                          for screen in "${detached_screens[@]}"; do
                          if [[ "${screen}" == *".pts"* ]]; then
                          IFS='.pts' read -ra split <<< "${screen}"
                          for id in "${split[@]}"; do
                          first_id="${id}"
                          break
                          done
                          break
                          fi
                          done

                          screen -R $first_id
                          fi


                          PS: If you would like to enable this for local terminal, remove && ! -z "${SSH_CLIENT} on the first line.







                          share|improve this answer








                          New contributor




                          Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          share|improve this answer



                          share|improve this answer






                          New contributor




                          Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          answered yesterday









                          Nicolas GarnierNicolas Garnier

                          1011




                          1011




                          New contributor




                          Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.





                          New contributor





                          Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          Nicolas Garnier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Super User!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f580087%2fautomatically-start-screen-upon-ssh-login%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Cannot install PyQt5 The Next CEO of Stack OverflowCannot install tcpreplay 3.4.4cannot...

                              Kapp-Putsch Acontecimentos | Outros artigos | Menu de navegação

                              Why did early computer designers eschew integers? The Next CEO of Stack OverflowWhat register...