Programmatically Change Apple’s Terminal Background
October 13, 2009
As an avid UNIX guy, one of the things that has always eluded me with Apple’s Terminal is that you can’t programmatically change the color assignments for the background and foreground. There have been many implementations that would open a new window with the color scheme that you wanted, however what I was looking to do was change the colors in the current window when I attempted to login to a remote server, and then change back when done.
What I stumbled over was the RandomColorTerminal script courtesy of the Red Sweater guys. Their code basically just grabs some random numbers and assigns it to the background, and then will set the foreground to white or black depending on the background color. I modified the code a bit to accept system variables instead of generating random numbers, which resulted in the ability to change the background to whatever color you wanted by simply assigning the variables to the RGB values you wanted. You can download the script HERE.
To make things easier, I also added some logic into my .profile to support this in a nicer context. You will need the add this into the beginning of your ~/.profile script.
settermcolor()
{
if [ "$TERM_PROGRAM" == "Apple_Terminal" ];then
export BG_RED=$1
export BG_GREEN=$2
export BG_BLUE=$3
osascript ~/Dropbox/Preferences/Scripts/Terminal/termcolor.scpt
fi
}
gtermcolors()
{
export BG_RED=$[ ($RANDOM % 65535) + 1 ]
export BG_GREEN=$[ ($RANDOM % 65535) + 1 ]
export BG_BLUE=$[ ($RANDOM % 65535) + 1 ]
osascript ~/Dropbox/Preferences/Scripts/Terminal/termcolor.scpt
echo "Color Assignments: $BG_RED $BG_GREEN $BG_BLUE"
}
remote_login()
{
argv=$@
cont=false
for item in $@;do
if [ "$(echo $item | grep "@")" != "" ];then
host=$(echo $item | cut -d "@" -f 2)
cont=true
fi
done
if [ "$cont" == "true" ];then
case $host in
nessus) settermcolor 0 0 0;;
infosec) settermcolor 0 0 0;;
*) reset_terminal;;
esac
ssh -Y $argv
reset_terminal
else
ssh -Y $argv
fi
}
alias reset_terminal="settermcolor 65535 65535 65535"
alias rebash="source ~/.profile ;reset_terminal"
alias ssh="remote_login"
Ssh sessions will now colorize based on host if you use username@host notation. You can set these up in the case statement in the remote_login function.




Recent Comments