Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

The following script closes a virtual machine (which is run in a screen session), waits for the session to close, creates a backup of the VM, and restarts the VM. The shutdown and bootup scripts speak for themselves, but I can post them if necessary. Is there any way to clean up the sockets_found function? It seems like there should be an easier way to detect whether or not screen has any open sessions.

#!/bin/bash

now=`date '+%Y%m%d'`

# No Sockets found
# There is a screen on
function sockets_found {
    screen -ls | grep "There is a screen on"
    if [ $? -eq 1 ]; then
        return 1
    else
        return 0
    fi
}

function wait_for_sockets_to_close {
    while sockets_found; do
        echo "Waiting for screen to close..."
        sleep 1
    done;
}

echo "Shutdown VM..."
/bin/bash ~/shutdown.sh
wait_for_sockets_to_close
# ensure that the backup directory exists
mkdir -p ~/backup
echo "Copying VM to backup directory..."
cp -Rf ~/VirtualBox\ VMs/ ~/backup/VirtualBox\ VMs${now}/
echo "Booting VM..."
/bin/bash ~/bootup.sh
share|improve this question
add comment

2 Answers

You also can find if the socket file exists on /var/run/screen/S-yourname/pid.screenname.

share|improve this answer
add comment

There is no need to grep here:

screen -ls | grep "There is a screen on"
if [ $? -eq 1 ]; then

Screen -ls will return with exit code 1 in the case no sockets are found in /var/run.

I would run the date command just before the copy is run, in case the sockets close during a date roll and you get the wrong date on your backup.

echo "Copying VM to backup directory..."
now=$(date '+%Y%m%d')
cp -Rf ~/VirtualBox\ VMs/ ~/backup/VirtualBox\ VMs${now}/

As above use $(cmd) notation instead of backtick notation. They achieve the same thing, but $() is visually clearer and can be nested.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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