Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Batch download code snippets

Batch download snippets from http://codesnippets.joyent.com and convert them to text files using man textutil (available on Mac OS X 10.4 or later).

Note: Old snippet versions will be automatically replaced by the downloaded snippets without a backup!

Author: jv
License: The MIT License, Copyright (c) 2008 jv

Usage:
# usage: bds [-p num] [-t tag] [-u user] tag
bds vim
bds -p 1280
bds -u jvs
bds -t plistbuddy
bds -t tar
bds -t ipfw -u jvs



#!/opt/local/bin/bash

# "batch download snippets" from http://codesnippets.joyent.com and
# convert them to text files using man textutil (available on Mac OS X 10.4 or later).
#
# Note: Old snippet versions will be automatically replaced by the downloaded snippets without a backup!
#      An alternative to man textutil is html2text, http://www.mbayer.de/html2text/ (which is available via MacPorts).
#
# Author: jv
# License: The MIT License, http://www.opensource.org/licenses/mit-license.php
# Copyright (c) 2008 jv
#
# cat /usr/local/bin/bds
#
# usage: bds [-p num] [-t tag] [-u user] tag


declare BaseURL='http://codesnippets.joyent.com'
declare download_dir="${HOME}/Desktop/Snippets"

# make sure there is no trailing slash
BaseURL="${BaseURL%/}"
download_dir="${download_dir%/}"

declare BasePostURL="${BaseURL}/posts/show"
declare BaseTagURL="${BaseURL}/tag"
declare BaseUserURL="${BaseURL}/user"

# make sure there is no trailing slash
BasePostURL="${BasePostURL%/}"
BaseTagURL="${BaseTagURL%/}"
BaseUserURL="${BaseUserURL%/}"


# man textutil
declare InputEncoding='utf-8'
declare OutputEncoding='utf-8'

export IFS=$' \t\n'


# function to download a single post specified by a post number: bds -p num
# cf. snippet, http://codesnippets.joyent.com/posts/show/1282

function snippet() {

   declare NL OPWD file outputfile postnum title url

   if [[ "${1//[[:digit:]]/}" != "" ]]; then echo "Argument error. No positive integer: ${1}"; return 1; fi

   postnum="${1}"
   url="${BasePostURL}/${postnum}"
   download_dir="${download_dir}/single-downloads"
   /bin/mkdir -p "${download_dir}"
   OPWD="${PWD}"
   cd "${download_dir}"
   /usr/bin/curl -L -O -s --max-time 25 "${url}" || exit 1    # download snippet web page
   file="${download_dir}/${url##*/}"
   trap '/bin/rm -f "${file}"; exit 0' 0 1 2 13 15

   # get title of downloaded web page
   #title="$(/usr/bin/sed -E -n -e '/<[tT][iI][tT][lL][eE]>/{s/^.*<[tT][iI][tT][lL][eE]>(.*)<\/[tT][iI][tT][lL][eE]>.*$/\1/p;q;}' "${file}" | \
   #         /usr/bin/sed -E -e 's/\[[^][:space:]]*\]//g')"    # delete [xxx] tag elements of title

   title="$(/usr/bin/egrep -m 1 -io '<title>.*</title>' "${file}" | /usr/bin/sed -E -e 's/^<title>[[:space:]]*|[[:space:]]*<\/title>$//g' \
             -e 's/\[[^][:space:]]*\]//g')"    # delete [xxx] tag elements of title


   title="${title//CodeSnippets:/}"
   title="${title//\//:}"
   title="${title// /_}"
   title="${title//[[:cntrl:]]/}"
   title="${title%"${title##*[!_]}"}"   # remove trailing underscores

   if [[ $title == '_CodeDrive_Snippets_courtesy_of_Peter_Coopers_handy_little_app' ]] || [[ -z "$title" ]]; then
      printf "\e[0K\e[31m%s\e[0m:  %s\n" "couldn't access" "${url}"
      /bin/rm "${file}"
      return 1
   fi

   outputfile="${download_dir}/${postnum}_${title}.txt"
   #outputfile="${download_dir}/${title}.txt"  # without post number prefix
   #outputfile="${outputfile//__/_}"  # uniq underscores

   printf "\n\e[0K\e[1;30m%s\e[0m:  %s\n\n" "saved as" "${outputfile}"

   /usr/bin/textutil -output "${outputfile}" -convert txt -inputencoding "${InputEncoding}" -encoding "${OutputEncoding}" "${file}"
   /bin/rm "${file}"

   # escape backslashes
   # man bash 2>/dev/null | less -p 'Each command in a pipeline'
   #outputfile="$(printf "%q" "${outputfile}")"  # cf. help printf
   outputfile="${outputfile//\\/\\\\}"

   NL=$'\\\n'

cat <<EOF | /bin/ed -s "${outputfile}"
H
,g/Snippets is a public source code repository/1,/Snippets is a public source code repository/d
,g/You need to create an account or log in to post comments to this site//You need to create an account or log in to post comments to this site/,\$d
,g|(See related posts)$|s|.See related posts.|${NL}${NL}|
,g|^to.* by.* on .*[[:digit:]]$|s|^to\(.*\) by\(.*\) on \(.*[[:digit:]]\)$|${NL}${NL}Author:\2${NL}Date: \3${NL}URL: ${url}${NL}Tags:\1${NL}|
,g|^Comments on this post$|s|\(Comments on this post\)|${NL}\1:|
,g| posts on .* at |s|\(.* posts on .* at .*\)|${NL}\1:|
w
EOF

# additional ed commands
# delete line numbers
# ,g|^[[:space:]]*[[:digit:]]\{1,\}[[:space:]]\{1,3\}|s|^[[:space:]]*[[:digit:]]\{1,\}[[:space:]]\{1,3\}\(.*\)$|\1|
# delete range of lines
# 4,11d


   cd "${OPWD}"
   return 0

}



#----------------------------------------- end of function snippet



declare pflag tflag uflag
declare cnt count dir_name file no_posts_check NL OPWD outputfile postnum tagsite title url urls website 

if [[ $# -eq 0 ]]; then 
   printf "%s\n%s\n" 'No arguments given!' "Usage: ${0##*/} [-p num] [-t tag] [-u user] tag" 1>&2
   exit 1
fi


while getopts ":p:t:u:" option
do
  case $option in
    p) pflag="$OPTARG" ;;
    t) tflag="$OPTARG" ;;
    u) uflag="$OPTARG" ;;
    [?]) printf "%s\n%s\n" 'Argument error!' "Usage: ${0##*/} [-p num] [-t tag] [-u user] tag" 1>&2; exit 1;;
    *) ;;
  esac
done

shift $(($OPTIND - 1))


if [[ $# -eq 1 ]]; then

   dir_name="${1}"
   tagsite="${BaseTagURL}/${1}"

elif [[ $# -gt 1 ]]; then

   printf "%s\n%s\n" 'Too many arguments!' "Usage: ${0##*/} [-p num] [-t tag] [-u user] tag" 1>&2
   exit 1

elif [[ -n "${pflag}" ]]; then
   snippet "${pflag}"
   exit 0

elif [[ -n "${tflag}" ]] && [[ -n "${uflag}" ]]; then

   dir_name="${tflag}-${uflag}"
   tagsite="${BaseUserURL}/${uflag}/tag/${tflag}"

elif [[ -n "${tflag}" ]]; then

   dir_name="${tflag}"
   tagsite="${BaseTagURL}/${tflag}"

elif [[ -n "${uflag}" ]]; then

   dir_name="${uflag}"
   tagsite="${BaseUserURL}/${uflag}"

else

   printf "%s\n%s\n" 'Argument error!' "Usage: ${0##*/} [-p num] [-t tag] [-u user] tag" 1>&2
   exit 1

fi


tagsite="${tagsite%/}"

#echo $dir_name
#echo $tagsite

count=1
cnt=0
curl_max_time=20
website=''
no_posts_check=''
NL=$'\\\n'
download_dir="${download_dir}/${dir_name//\//:}"
download_dir="${download_dir%/}"
/bin/mkdir -p "${download_dir}"
OPWD="${PWD}"
cd "${download_dir}"

# print download directory
printf "\n\e[0K\e[1;30m%s\e[0m:  %s\n\n" "download directory" "${download_dir}"


while [[ -z "${no_posts_check}" ]]; do

   # download website of the form: 
   # http://somewebsite.com/tag/bash/1,
   # http://somewebsite.com/user/name/1 or 
   # http://somewebsite.com/user/name/tag/bash/1

   website="$(/usr/bin/curl -L -s --max-time $curl_max_time "${tagsite}/${count}" )"

   if [[ $? -ne 0 ]]; then 
      printf "\e[0K\e[31m%s\e[0m:  %s\n" "curl_max_time ${curl_max_time}" "${tagsite}/${count}"
      exit 1
   fi

   #if [[ -n "$(printf "%s" "${website}" | /usr/bin/egrep -o 'Application error \(Apache\)')" ]]; then 
      #no_posts_check='Application error (Apache)'
      #printf "\e[0K\e[31m%s\e[0m:  %s\n" "no further posts" "${no_posts_check}"
   #fi

   if [[ -n "$(printf "%s" "${website}" | /usr/bin/egrep -o '>No posts<')" ]]; then 
      no_posts_check='>No posts<'
      #printf "\e[0K\e[31m%s\e[0m:  %s\n" "no further posts" "${no_posts_check}"
   fi

: <<-'COMMENT'

   # works for Bash 3.0 or later
   if [[ "${website}" =~ '>No posts<' ]]; then 
      no_posts_check="${BASH_REMATCH[0]}"
      #printf "\e[0K\e[31m%s\e[0m:  %s\n" "no further posts" "${no_posts_check}"
   fi

COMMENT


   if [[ -z "${no_posts_check}" ]]; then

      # extract relevant post URLs
      #urls=( $(printf "%s\n" "${website}" | /usr/bin/sed -E -n -e "s|^.* href=\"(/posts/show/[[:digit:]]+)\".*$|${BaseURL}\1|p;g") )
      urls=( $(printf "%s\n" "${website}" | /usr/bin/egrep -o 'href="/posts/show/[[:digit:]]+"' | /usr/bin/sed -E -n -e "s|href=\"(/posts/show/[[:digit:]]+)\"|${BaseURL}\1|p;g") )

      for ((i=0; i < "${#urls[@]}"; i++)); do

         url="${urls[${i}]}"

         postnum="${url##*/}"
         file="${download_dir}/${postnum}"
         trap '/bin/rm -f "${file}"; exit 0' 0 1 2 13 15

         /usr/bin/curl -L -O -s --max-time $curl_max_time "${url}"

         if [[ $? -ne 0 ]]; then 
            printf "\e[0K\e[31m%s\e[0m:  %s\n" "curl_max_time ${curl_max_time}" "${url}"
            continue
         fi
 

         # get title of downloaded web page
         #title="$(/usr/bin/sed -E -n -e '/<[tT][iI][tT][lL][eE]>/{s/^.*<[tT][iI][tT][lL][eE]>(.*)<\/[tT][iI][tT][lL][eE]>.*$/\1/p;q;}' "${file}" | \
         #    /usr/bin/sed -E -e 's/\[[^][:space:]]*\]//g')"    # delete [xxx] tag elements of title

         title="$(/usr/bin/egrep -m 1 -io '<title>.*</title>' "${file}" | /usr/bin/sed -E -e 's/^<title>[[:space:]]*|[[:space:]]*<\/title>$//g' \
                -e 's/\[[^][:space:]]*\]//g')"    # delete [xxx] tag elements of title


         title="${title//CodeSnippets:/}"
         title="${title//\//:}"
         title="${title// /_}"
         title="${title//[[:cntrl:]]/}"
         title="${title%"${title##*[!_]}"}"   # remove trailing underscores

         #printf "%s\n" "${title}"

         if [[ $title == '_CodeDrive_Snippets_courtesy_of_Peter_Coopers_handy_little_app' ]] || [[ -z "$title" ]]; then
            printf "\e[0K\e[31m%s\e[0m:  %s\n" "couldn't access" "${url}"
            /bin/rm "${file}"
            continue
         fi

         outputfile="${download_dir}/${postnum}_${title}.txt"
         #outputfile="${download_dir}/${title}.txt"  # without post number prefix
         #outputfile="${outputfile//__/_}"  # uniq underscores

         let cnt++
         printf "\e[0K\e[1;32m%-6s\e[0m  %s\n" "${cnt}" "${outputfile##*/}"

         /usr/bin/textutil -output "${outputfile}" -convert txt -inputencoding "${InputEncoding}" -encoding "${OutputEncoding}" "${file}"

         /bin/rm "${file}"


         # escape backslashes
         # man bash 2>/dev/null | less -p 'Each command in a pipeline'
         #outputfile="$(printf "%q" "${outputfile}")"  # cf. help printf
         outputfile="${outputfile//\\/\\\\}"

# edit $outputfile in-place with man ed
# first delete lines at the beginning & end,
# then remove the string 'See related posts' and add some newlines with $NL,
# then convert the line 'to...by...on' to line 'Author:...', line 'Date:...', line 'URL:...' and line 'Tags:...'
# and finally the last two ed commands insert two further newlines with $NL

cat <<EOF | /bin/ed -s "${outputfile}"
H
,g/Snippets is a public source code repository/1,/Snippets is a public source code repository/d
,g/You need to create an account or log in to post comments to this site//You need to create an account or log in to post comments to this site/,\$d
,g|(See related posts)$|s|.See related posts.|${NL}${NL}|
,g|^to.* by.* on .*[[:digit:]]$|s|^to\(.*\) by\(.*\) on \(.*[[:digit:]]\)$|${NL}${NL}Author:\2${NL}Date: \3${NL}URL: ${url}${NL}Tags:\1${NL}|
,g|^Comments on this post$|s|\(Comments on this post\)|${NL}\1:|
,g| posts on .* at |s|\(.* posts on .* at .*\)|${NL}\1:|
w
EOF

# additional ed commands
# delete line numbers
# ,g|^[[:space:]]*[[:digit:]]\{1,\}[[:space:]]\{1,3\}|s|^[[:space:]]*[[:digit:]]\{1,\}[[:space:]]\{1,3\}\(.*\)$|\1|
# delete range of lines
# 4,11d


      done  # for

      let count++

   fi

done   # while


   cd "${OPWD}"


exit 0

ANSI terminal color chart

1.
#!/bin/bash
#
#   This file echoes a bunch of color codes to the 
#   terminal to demonstrate what's available.  Each 
#   line is the color code of one forground color,
#   out of 17 (default + 16 escapes), followed by a 
#   test use of that color on all nine background 
#   colors (default + 8 escapes).
#
#   Author: Giles Orr
#   URL: http://gilesorr.com/bashprompt/howto/c350.html
#   License: GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation;
#            http://gilesorr.com/bashprompt/howto/a1004.html


T='gYw'   # The test text

echo -e "\n                 40m     41m     42m     43m\
     44m     45m     46m     47m";

for FGs in '    m' '   1m' '  30m' '1;30m' '  31m' '1;31m' '  32m' \
           '1;32m' '  33m' '1;33m' '  34m' '1;34m' '  35m' '1;35m' \
           '  36m' '1;36m' '  37m' '1;37m';
  do FG=${FGs// /}
  echo -en " $FGs \033[$FG  $T  "
  for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
    do echo -en "$EINS \033[$FG\033[$BG  $T  \033[0m";
  done
  echo;
done
echo

2.
#!/bin/sh
#
#  colors v1.03
#
#  A simple shell script to output an ANSI terminal color chart.
#  It may be useful when trying to customize your ANSI terminal
#  color scheme!
#
#  Written and placed in the public domain by Ian Abbott <ian@abbott.org>
#
#  ANSI terminal color chart generator
#  Author: Ian Abbott
#  License: BSD License, http://www.opensource.org/licenses/bsd-license.php
#  URL: http://www.snippetcenter.org/de/ansi-terminal-color-chart-generator-s1346.aspx

for h in 0 1; do
  echo -e "\\033[0;${h}m\\c"
  case $h in
  0) echo -e "Normal\\c" ;;
  1) echo -e "High\\c" ;;
  esac
  echo -e " intensity foreground (background color in parentheses)\\033[m"
  for f in 0 1 2 3 4 5 6 7; do
    for b in 0 1 2 3 4 5 6 7 8; do
      echo -e "\\033[${h};3${f}\\c"
      if [ $b -lt 8 ]; then
        echo -e ";4${b}m\\c"
      else
        echo -e "m\\c"
      fi
      case $f in
      0) echo -e " BLACK \\c" ;;
      1) echo -e "  RED  \\c" ;;
      2) echo -e " GREEN \\c" ;;
      3) echo -e " YELLOW\\c" ;;
      4) echo -e "  BLUE \\c" ;;
      5) echo -e "MAGENTA\\c" ;;
      6) echo -e "  CYAN \\c" ;;
      7) echo -e " WHITE \\c" ;;
      esac
      case $b in
      8) echo -e "\\033[m" ;;
      *) echo -e " \\033[m \\c" ;;
      esac
    done
  done
  echo -e "\\033[${h}m\\c"
  for b in 0 1 2 3 4 5 6 7 8; do
    case $b in
    0) echo -e "(black)  \\c" ;;
    1) echo -e " (red)   \\c" ;;
    2) echo -e "(green)  \\c" ;;
    3) echo -e "(yellow) \\c" ;;
    4) echo -e " (blue)  \\c" ;;
    5) echo -e "(magenta)\\c" ;;
    6) echo -e " (cyan)  \\c" ;;
    7) echo -e "(white)  \\c" ;;
    8) echo -e " (none)\\c" ;;
    esac
  done
  echo -e "\\033[m\\n"
done

Terminal window commands

# Inspired by: 
# - Re-size and Move with Escape Sequences, http://www.osxfaq.com/tips/unix-tricks/week99/monday.ws
# - Define Aliases and Functions, http://www.osxfaq.com/tips/unix-tricks/week99/tuesday.ws
# - Focus and Dock with Escape Sequences, http://www.osxfaq.com/Tips/unix-tricks/week99/wednesday.ws
# Author: Adrian Mayo, http://101.1dot1.com and http://www.peachpit.com/title/0321374118
# also see: http://en.wikipedia.org/wiki/ANSI_escape_code

function title() { if [[ $# -eq 1 && -n "$@" ]]; then printf "\e]0;${@}\a"; fi; return 0; }  
function title() { if [[ -n "$@" ]]; then printf "\033]0;${1}\007"; fi; return 0; }
function docktw() { printf "\e[2t"; return 0; }
function docktw() { printf "\e[2t"; sleep 5; printf "\e[5t"; return 0; }
function bgtw() { printf "\e[6t"; return 0; }
function bgtw() { printf "\e[6t"; sleep 5; printf "\e[5t"; return 0; }    # background the Terminal window

title 'Hello, world!'
docktw
bgtw


# positive integer test (including zero)
function positive_int() { return $(test "$@" -eq "$@" > /dev/null 2>&1 && test "$@" -ge 0 > /dev/null 2>&1); }

# move the Terminal window
function mvtw() { 
   if [[ $# -eq 2 ]] && $(positive_int "$1") && $(positive_int "$2"); then 
      printf "\e[3;${1};${2};t"
      return 0
   fi
   return 1
}


# resize the Terminal window
function sizetw() { 
   if [[ $# -eq 2 ]] && $(positive_int "$1") && $(positive_int "$2"); then 
      printf "\e[8;${1};${2};t"
      /usr/bin/clear
      return 0
   fi
   return 1
}


# full screen
function fscreen() { printf "\e[3;0;0;t\e[8;0;0t"; /usr/bin/clear; return 0; }

# default screen
function dscreen() { printf "\e[8;35;150;t"; printf "\e[3;300;240;t"; /usr/bin/clear; return 0; }

# max columns
function maxc() { printf "\e[3;0;0;t\e[8;50;0t"; /usr/bin/clear; return 0; }

# max rows
function maxr() { printf "\e[3;0;0;t\e[8;0;100t"; /usr/bin/clear; return 0; }

# show number of lines & columns
function lc() { printf "lines: $(/usr/bin/tput lines)\ncolums: $(/usr/bin/tput cols)\n"; return 0; }

# move cursor
function mvc() { 
   if [[ $# -eq 2 ]] && $(positive_int "$1") && $(positive_int "$2"); then 
      /usr/bin/tput cup "$1" "$2"
      /usr/bin/tput el  # clear to end of line
      #/usr/bin/tput ed
      return 0
   fi
   return 1

}


# wrap lines according to the number of columns of the Terminal window
function wraptw() { 
   declare str var=$(/usr/bin/tput cols)
   if [[ -s /dev/stdin ]]; then str="$(</dev/stdin)"; else str="$@"; fi 
   printf "%s\n" "$str" | /usr/bin/fmt -w $var
   #printf "%s\n" "$str" | /usr/bin/fold -w $(/usr/bin/tput cols)
   return 0
}


long_line="$(/usr/bin/jot -b 'This is a test sentence!' 100 | /usr/bin/tr '\n' ' ')"
printf "%s\n" "$long_line" | wraptw

lc
mvtw 0 0
mvtw 0 300
mvtw 300 300
mvtw 80 140
fscreen
dscreen
maxc
maxr

lc
sizetw 0 0
sizetw 0 50
sizetw 1 50
sizetw 50 50
sizetw 50 500
sizetw 50 150

mvc 2 45
mvc 100 23
mvc 99 3

dscreen


#-----------------------------------------------------


# customize the Terminal window's title bar text

# show the current date as title bar text
declare -x PROMPT_COMMAND='printf "\e]0; $(/bin/date)\a"'   
declare -x PROMPT_COMMAND='printf "\e]0;$(/bin/date "+%a %b %e   %H:%M:%S ")\a"'
declare -x PROMPT_COMMAND='printf "\e]0;$(/bin/date "+%Y-%m-%d   %H:%M:%S ")\a"'

# show current working directory 
declare -x PROMPT_COMMAND='printf "\e]0;$(/bin/pwd) \a"'
declare -x PROMPT_COMMAND='printf "\e]0;$(/bin/pwd | /usr/bin/tr -d "[[:cntrl:]]") \a"'

# show OLDPWD 
declare -x PROMPT_COMMAND='printf "\e]0;$(printf %s "$OLDPWD") \a"'
declare -x PROMPT_COMMAND='printf "\e]0;$(printf %s "$OLDPWD" | /usr/bin/cut -c 1-100) \a"'

export -p | grep -i PROMPT_COMMAND
env | grep -i PROMPT_COMMAND
unset -v PROMPT_COMMAND


# first create environment variable TITLE 
# cf. Prompt Commands, http://www.osxfaq.com/Tips/unix-tricks/week71/wednesday.ws
# Author: Adrian Mayo, http://101.1dot1.com and http://www.peachpit.com/title/0321374118

unset -v TITLE PROMPT_COMMAND
declare -x TITLE="Terminal"
declare -x PROMPT_COMMAND='printf "\e]0;${TITLE}\a"'

# message as title bar text
function message_title() { 
   if [[ $# -eq 1 && -n "$@" ]]; then 
      #TITLE="$@"
      TITLE="$(printf %s "$@" | /usr/bin/cut -c 1-100)"
   fi
   return 0
}

export -f message_title
export -p | grep -i message_title
env | grep -i message_title
#unset -f message_title 

message_title 'Hello, world!'


# show OS information in title bar
function osinfo() { 
   x1="$(/usr/bin/sw_vers -productName)"
   x2="$(/usr/bin/sw_vers -productVersion)"
   x3="$(/usr/bin/sw_vers -buildVersion)"
   x4="$(/usr/bin/arch)"
   TITLE="${x1} - ${x2} - ${x3} - ${x4}"
   return 0
}

export -f osinfo
osinfo


function eval_title() { 
   if [[ -n "$(printf %s "$@") | /usr/bin/egrep '^date|whoami|logname|uname|machine|pwd|hostname$'" ]]; then 
      cmd_output="$(eval "$@")"
      TITLE="$cmd_output"
   fi
   return 0
}
export -f eval_title

eval_title "date"
eval_title "whoami"
eval_title "logname"
eval_title "uname"
eval_title "machine"
eval_title "pwd"
eval_title "hostname"


function date_title() { TITLE="$(/bin/date "+%Y-%m-%d")"; return 0; }
export -f date_title
date_title

function logname_title() { TITLE="$(/usr/bin/logname)"; return 0; }
export -f logname_title
logname_title


# show last command in title bar
help fc
unset -v TITLE PROMPT_COMMAND
declare -x PROMPT_COMMAND='printf %b "\e]0;$(fc -ln | tail -n 1 | cut -c 2-150 | tr -d "\\")\a"'


# show current command in title bar
help history
unset -v TITLE PROMPT_COMMAND
declare -x PROMPT_COMMAND='printf %b "\e]0;$(history 1 | /usr/bin/cut -c 8-150 | tr -d "\\")\a"'
declare -x PROMPT_COMMAND='printf %b "\e]0;$(history 1 | sed -E "s/^[[:space:]]*[[:digit:]]+[[:space:]]+(.*)$/\\1/" | cut -c 1-150 | tr -d "\\")\a"'


#-----------------------------------------------------


# increase font size
function ifont() { 
/usr/bin/osascript <<__END__
    tell application "System Events" to tell process "Terminal" to keystroke "+" using command down
__END__
  return 0 
}

ifont


# decrease font size
function dfont() { 
/usr/bin/osascript <<__END__
    tell application "System Events" to tell process "Terminal" to keystroke "-" using command down
__END__
  return 0 
}

dfont


# hide all Terminal windows
function hideall() { 
   /usr/bin/osascript -e 'tell application "System Events" to set visible of some item of ( get processes whose name = "Terminal" ) to false'
   return 0
}

hideall


# create a new Terminal window and cd to the same current working directory
# cf. http://justinfrench.com/index.php?id=231

unset -f newin

function newin() {
   /bin/pwd | /usr/bin/pbcopy
   /usr/bin/open -a Terminal
   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "cd \"$(/usr/bin/pbpaste)\"; echo \" \" | /usr/bin/pbcopy; /usr/bin/clear"'
   return 0 
}

cd ~/Desktop
newin

backup files

// create backup copy

#!/bin/bash

filename=$1
date=`date +%Y%m%d`

usage () {
        echo "Usage: `basename $0` filename"
}

if [ -z "$filename" -a ! -f "$filename" ]; then
        usage
        exit 1
fi

rev=0
backup="$filename.$date.$rev"

while [ -f $backup ]; do
        let rev+=1
        backup="$filename.$date.$rev"
done

cp $filename $backup
exit $?

Rewrite SPAM subject line with procmail

// Remove textdrive's ***SPAM*** addition
// by phearlez
// http://discuss.joyent.com/viewtopic.php?pid=154695#p154695

# Remove the word ***SPAM*** from SpamAssassin's subject line re-write

 :0 fHw
 * ^Subject: \*\*\*SPAM\*\*\*
 | sed -e 's/\*\*\*SPAM\*\*\*//g'

JS Regex's for sourcecode

Extracted from SyntaxHilighter

	MultiLineCComments : new RegExp('/\\*[\\s\\S]*?\\*/', 'gm'),
	SingleLineCComments : new RegExp('//.*$', 'gm'),
	SingleLinePerlComments : new RegExp('#.*$', 'gm'),
	DoubleQuotedString : new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'),
	SingleQuotedString : new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'", 'g')

Substrings in Ruby

The other day I was wondering why some really simple Ruby code of mine wasn’t working. The code under test looked something like this:

    def find_directories
        directories = []
        entries = `ls -l`.split/\n/  # get long-format directory listing
        entries.shift   # toss away the totals line
        entries.each do |entry|
            is_directory = (entry[0] == 'd')  # is it a directory?
            directories &lt;&lt; dir if is_directory
        end
        directories
    end

I figured that my ls -l.split/\n/ trickery wasn’t working. So I fired up irb and tried it manually. It worked fine.
Then I sprinkled a few puts statements throughout. entries was fine, and each entry was perfect, looking something like this:
drwx------ 24 jcohen jcohen 816 Aug 19 11:04 Documents

I couldn’t figure out what was wrong. All I had to do was look at the first character of entry; if it was a ‘d’, then I knew I had a directory. But for some reason, is_directory was always false. I googled, checked the RDocs for the String class, thumbed through the PickAxe, and something I read triggered one of those ah-ha moments.
Rats: My C# brain is still alive and kicking.

To confirm my fears, I fired up irb again:

irb> s = "Jeff" 
=> "Jeff" 
irb> s[0]
=> 74

That’s right, folks: on a string, the bracket syntax – when given only one parameter – will return the ASCII value of the character inside. Not the actual character, as it will in C#.
To correctly grab a one-character substring from a string, you have to supply two parameters:

irb> s[0,1]
=> "J" 

Publishing raw code

Here is how to add code to a blog post in a way that you can see the code...so you can show the actual raw code without it actually working.

&lt;strong&gt;hello&lt;/strong&gt;


Just incase the head and tail in the code tags.

This is handy, I can keep this code here, as I was always searching for where I kept this handy info...now I have a place where I can quickly find all my code, and better still I'm sharing it by default.