Bash & Screen

You may be familiar with my tutorial on getting your ssh-agent to work inside screen. If not, have a look.

There’s always room for improvements! Here’s an excerpt from my current .bash_profile:

function Attach(){
    grabssh
    if [[ -z "${1}" ]] ; then
        local n=`screen -wipe | egrep -i 'attached|detached' | wc -l`
        if [[ "${n}" -gt 1 ]]; then
            check_screen
            return
        fi
    fi
    echo screen -d -R ${*}
    screen -d -R ${*}
}

check_screen () {
  # Look in the path?
    type screen > /dev/null 2>&1
    if [[ ${?} = 0 ]]; then
        tmp=0
        echo
        for scr in `screen -wipe | egrep -i 'attached|detached' | awk '{print $1"_"$2}'`
        do
            echo "Screen available: ${scr}"
            if [[ ${tmp} -eq 0 ]] ; then
                myscreen=${scr%_*}
            fi
            tmp=$(($tmp+1))
        done
        if [[ -n "${myscreen}" ]] ; then
            echo
            echo "Enter to attach to ${myscreen},"
            echo "'n' to move on,"
            echo "unique bits to attach elsewhere"
            read eon
            if [[ -z "${eon}" ]] ; then
                [[ -z "${myscreen}" ]] && return
                eon=${myscreen}
            fi
            if [[ "${eon}" != 'n' ]] ; then
                Attach ${eon}
            fi
        fi
    fi
}

[[ -n "$PS1" ]] && check_screen

If screen(s) exist, I’m presented with a list of them on login. I’m then able to hit return for a default, or type in which of them I wish to resume.

If I don’t want to resume any screen I can simply hit ‘n’ and go on about my day.

The Attach and check_screen functions are actually in a different file that is sourced by .bashrc and conditionally by .bash_login. This allows the functions to be used in non-login shells (in local terminal windows for example).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.