Matt P
Matt P

Reputation: 163

Bash script to alias ssh. Better/optimal way to do this?

I wrote the following script to change the color of the shell depending on which host I'm trying to connect to. And, although it works, I'm wondering if there's a better way to do things? Specifically, is there a more cross-shell way of changing the prompt color? Also, is there a better approach to applying a regex to the host name (outside of grep/ack)?

Either case, here's the code:

function ssh() {

    #save all args (makes it easier to pass to ssh later)
    local all_args=$*

    #save path to ssh exec in current $PATH
    local ssh_path=$(which ssh)

    # host is second to last arg. see ssh -h
    local host=${@:(-2):1}


    #### color codes for tput ####
    # setaf=foreground, setab=background
    # 0 Black
    # 1 Red
    # 2 Green
    # 3 Yellow
    # 4 Blue
    # 5 Magenta
    # 6 Cyan
    # 7 White
    # sgr0 reset
    ##############################

    #### Or if you're on a Mac ####
    # you can use an AppleScript to
    # change to a different Terminal
    # setting. I use Pro (white/black)
    # by default, but jump to a custom
    # one called 'mpowell-md' which
    # is a shade of red when connecting
    # to mpowell-md
    ###############################

    case $host in

            # can use basic regex here
            *mpowell\-md*)
                    # osascript -e "tell application \"Terminal\" to set current settings of first window to settings set named \"mpowell-md\""
                    tput setaf 1;#red
            ;;

            # default case
            *)
                    # could default to setting it back to Pro, etc...
                    # osascript -e "tell application \"Terminal\" to set current settings of first window to settings set named \"Pro\""
            ;;
    esac

    #run and wait for ssh to finish
    eval "$ssh_path $all_args"


    tput sgr0;#reset
    #osascript -e "tell application \"Terminal\" to set current settings of first window to settings set named \"Pro\""
}

Let me know what you think, and thanks!

- Matt

Upvotes: 1

Views: 605

Answers (1)

Matt
Matt

Reputation: 8476

PS1 works quite well as a relatively non invasive but prominent place to give a visual indicator on where you are. It also leaves the rest of the shell untouched which is important if you have colours active in the shell in other ways (like showing files of different types in different colours).

For example we apply this style to boxes & use different colours for prod, uat, stg, dev etc

e.g.

PS1="[\!]:[\w]\n[\u@\h] \[\033[1m\]\[\033[41m\] $SOME_VARIABLE \[\033[0m\] $ "

so this gives a 2 line prompt like

[501]:[/home/matt]
[matt@mybox] FOO $ 

where FOO has a solid red background (in this example).

PS1 is a sh (and variants) feature btw.

Upvotes: 3

Related Questions