I have made a bash file which launches another bash file in a detached screen with a unique name, I need to ensure that only one instance of that internal bash file is running at any one point in time. To do this, I want to make the parent bash file check to see if the screen by that name exists before attempting to create it. Is there a method to do this?
When checking if a file exists, the most commonly used FILE operators are -e and -f . The first one will check whether a file exists regardless of the type, while the second one will return true only if the FILE is a regular file (not a directory or a device).
Method 2 - Using Screen prefix key To check whether we are in Screen session or not, simply press Ctrl+a and then Ctrl+t keys. This will show the time and host name if you are in Screen session.
1) By entering the file name in the terminal: Open the “testfile.sh” in any text editor. Then write the script, save it by pressing “save”. One way is to find a file by asking for a filename from the user in the terminal. Use “-f” to check the file's existence.
Within a single screen session, you can also name each window. Do this by typing Ctrl + A , A then the name you want. You can view an interactive list of named windows by typing Ctrl + A , " , and select the one you want to switch to from that list.
You can grep the output of screen -list
for the name of the session you are checking for:
if ! screen -list | grep -q "myscreen"; then
# run bash script
fi
You can query the screen 'select' command for a particular session; the shell result is '0' if the session exists, and '1' if the named screen session is not found:
$ screen -S Tomcat $ screen -S Tomcat -Q select . ; echo $? 0
versus:
$ screen -S Jetty -Q select . ; echo $? No screen session found. 1
Note that the '.'
after the select
is optional, but may be more robust.
Given I can't comment I am posting this as a new answer. troyfolger's answer is a good idea and basically amounts to try and send the session a command that will do very little. One issue is that for some (older) versions of screen -Q isn't supported and so for those versions the correct command is
screen -S Jetty -X select . ; echo $?
Which send the command "select ." to the screen session called "Jetty".
Select changes which window is active and . means the current active window so this means try and change the active window to the currently active window. This can only fail if there isn't a session to connect to which is what we wanted.
If you read the info docs than it does suggest that the only use of select . is with -X as a test or to make sure something is selected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With