How do I make the apple terminal window auto change colour scheme when I ssh to a specific server

前端 未结 10 1817
甜味超标
甜味超标 2020-12-12 12:58

When I ssh into a remote production server I would like the colour scheme of my terminal window to change to something brigh and scary, preferably red, to warn me that I am

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 13:29

    Xterm-compatible Unix terminals have standard escape sequences for setting the background and foreground colors. I'm not sure if Terminal.app shares them; it should.

    case $HOSTNAME in
        live1|live2|live3) echo -e '\e]11;1\a' ;;
        testing1|testing2) echo -e '\e]11;2\a' ;;
    esac
    

    The second number specifies the desired color. 0=default, 1=red, 2=green, etc. So this snippet, when put in a shared .bashrc, will give you a red background on live servers and a green background on testing ones. You should also add something like this to reset the background when you log out.

    on_exit () {
        echo -e '\e]11;0\a'
    }
    trap on_exit EXIT
    

    EDIT: Google turned up a way to set the background color using AppleScript. Obviously, this only works when run on the same machine as Terminal.app. You can work around that with a couple wrapper functions:

    set_bg_color () {
        # color values are in '{R, G, B, A}' format, all 16-bit unsigned integers (0-65535)
        osascript -e "tell application \"Terminal\" to set background color of window 1 to $1"
    }
    
    sshl () {
        set_bg_color "{45000, 0, 0, 50000}"
        ssh "$@"
        set_bg_color "{0, 0, 0, 50000}"
    }
    

    You'd need to remember to run sshl instead of ssh when connecting to a live server. Another option is to write a wrapper function for ssh that scans its arguments for known live hostnames and sets the background accordingly.

提交回复
热议问题