Never been to TextSnippets 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!)

« Newer Snippets
Older Snippets »
Showing 21-40 of 74 total

List 10 largest files/directories within the current directory

du -sk * | sort -nr | tail -10

twitter from the command line

Replace username/password with your info. The message is posted as the status text.

curl -u username:password -d status="" http://twitter.com/statuses/update.xml

Easy way to zip dirs in zsh

This is just a quick way to zip dirs from zsh, while ignoring unwanted files like .DS_Store and .svn/*.

zipdir() { zip "$@".zip -r "$@" -x "*/.DS_Store" "*/.svn/*" }

quicksilver tags in geektool script version 3

// can anyone tell me what this is? Is it applescript?
How do I call it from geektool? I found this here
http://theappleblog.com/community/development/588-displaying-quicksiler-tags/#post6596

set QuicksilverTags to (path to home folder as string) & "Library:Caches:Quicksilver:Indexes:QSPresetQSFileTagsPlugIn.qsindex"

do shell script "grep string " & (quoted form of POSIX path of QuicksilverTags) & " | awk {'print $1'}"

set theTags to result

--> From the MacScripter.net Text Delimiters Tutorial.
set newText to switchText of theTags from "qs.tag.file" to ""
to switchText of currentText from SearchString to ReplaceString
        set storedDelimiters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to SearchString
        set currentText to currentText's text items
        set AppleScript's text item delimiters to ReplaceString
        set currentText to currentText as Unicode text
        set AppleScript's text item delimiters to storedDelimiters
        
        currentText
        
        set this_text to currentText
        
        set new_text to ""
        
        --> From the MacScripter Forum.
        repeat with myPara in paragraphs of this_text
                if new_text does not contain myPara then set new_text to new_text & myPara & return
        end repeat
        set new_text to (characters 1 thru -2 of new_text) as text
        
        set more_text to new_text
        set replace_text to ""
        
        --> From MacScripter Forum.
        repeat with myPara in paragraphs of more_text
                
                if replace_text does not contain myPara then set replace_text to replace_text & (text 9 thru -10 of myPara) & return
        end repeat
        
        set output to "Tags: " & return & replace_text
        
end switchText -- the end of the handler.

quicksilver tags in geektool

// this code taken from http://bbs.applescript.net/viewtopic.php?id=20330

do shell script "grep string /Users/username/Desktop/QSPresetQSFileTagsPlugIn.qsindex | awk {'print $1'}"

set theTags to result

set newText to switchText of theTags from "qs.tag.file" to ""

to switchText of currentText from SearchString to ReplaceString -- the handler
   
   set storedDelimiters to AppleScript's text item delimiters
   -- this simply stores the current value of AppleScript's AppleScript's text item delimiters
   -- so they can be restored later (thus helping to avoid potential problems elsewhere).
   -- Remember, we always set them back to what they were.
   
   set AppleScript's text item delimiters to SearchString
   -- AppleScript's AppleScript's text item delimiters are now set to "Purple"
   
   set currentText to currentText's text items -- note we have changed currentText's value
   -- create a list of text items from the original text, separated at the points where the
   -- current text item delimiter ("Purple") appeared.
   --> {"What, ", " Shoes?"} - Note that the spaces and punctuation are retained.
   
   set AppleScript's text item delimiters to ReplaceString
   -- AppleScript's AppleScript's text item delimiters are now set to "Green"
   
   set currentText to currentText as Unicode text
   -- coerce the list {"What, ", " Shoes?"} to Unicode text. This operation will also
   -- insert the current value of AppleScript's AppleScript's text item delimiters ("Green")
   -- between each of the listed items
   
   --> "What, Green Shoes?"
   
   set AppleScript's text item delimiters to storedDelimiters
   -- restore the value of AppleScript's AppleScript's text item delimiters
   -- to whatever they were on entering the subroutine. Remember that a call to this
   -- might have been made from within a section of script that had the TIDs set to
   -- something else. Hand the result back with the TIDs as they were.
   
   currentText
   -- return the now modified text (and restored TIDs) -- "What, Green Shoes?"
   
   
   set this_text to currentText
   
   set new_text to ""
   
   --Loop through paragraphs of old text
   repeat with myPara in paragraphs of this_text
       --Check for paragraph’s contents in new text
       --If not there add new text to end of new text
       if new_text does not contain myPara then set new_text to new_text & myPara & return
   end repeat
   --Remove final return
   set new_text to (characters 1 thru -2 of new_text) as text
   
end switchText -- the end of the handler.

TPUT and TERMINFO

Using the command line as UI ? try to remember some of these useful commands !

# save cursor position
tput sc
# move cursor to 10th line and 20th column
tput cup 10 20
# write some text from here in standout mode
tput smso
echo "j ecris a partir de la 10eme ligne et la 20eme colonne"     
# restore cursor position
tput rc
# exit from standout mode
tput rmso


Some more advanced stuff can be done :
# save your prompt
PS1_SAVE=$PS1
# set the prompt to blank
PS1=''
# save the number of colums of the terminal
COLUMNS=$(tput cols)
# save the number of lines of the terminal
LINES=$(tput lines)
# set the message you want to display (here it's "hello I am at the center of the term")
message="coucou je suis au milieu du terminal"
# get the horizontal position to center your text
hpos=$(expr $LINES / 2)
# get the vertical position to center your text
vpos=$(expr \( $COLUMNS - $(echo "$message" | wc -c) \) / 2)
# move the cursor to that position
tput cup $hpos $vpos
# enter in reverse video mode
tput rev
# display the message
echo "$message"
# wait for 3 second to see the message
sleep 3
# recall your default prompt
PS1=$PS1_SAVE
# reset all terminal settings
tput sgr0
# clear the screen
tput clear

STTY Control Assignements

Using puTTY and not able to set a correct configuration for your UNIX-like system ?
Try using the "stty" command.

For example on my HP-UX 11.11 box I have added the following in my .profile :
stty erase "^H" kill "^U" intr "^C" eof "^D" susp "^Z"

Remove CVS directoires and files

When check out the files, use
cvs export

instead of
cvs checkout

can avoid creating those CVS directories

If files already exist, then in bash, do
find . -name CVS -prune -exec rm -rf {} \;

Bar graph of file, folder sizes on TxD

From besonen.

Prints an ordered list of file and folder sizes in human readable form, with a bar graph to show the relative size of each item.

du -k | sort -n | perl -ne 'if ( /^(\d+)\s+(.*$)/){$l=log($1+.1);$m=int($l/log(1024)); printf("%6.1f\t%s\t%25s  %s\n",($1/(2**(10*$m))),(("K","M","G","T","P")[$m]),"*"x (1.5*$l),$2);}'

Find out if a mac is PPC/Intel in bash

// This checks the processor type in bash

if [[ `sysctl hw.machine` = "hw.machine: Power Macintosh" ]]; then 
        PROCESSOR='PowerPC'
else
        PROCESSOR='Intel'
fi

sup: bash script for universal SCM syncing (svn, svk, cvs, darcs, etc.)

I really can never remember if the project I'm in uses svn or cvs or if it's my own local svk mirror, etc. etc. Thus was born 'sup'!

Save and drop into a location that's in your PATH (I use ~/bin, YMMV)

#!/bin/bash
# sup -- a quick bash script to sync w/ various SCM tools
# @author   Jamie Wilkinson 

HERE=$(pwd)

# subversion
if [ -e ".svn" ]; then
        svn up
# cvs
elif [ -e "CVS" ]; then
        cvs up
# darcs
elif [ -e "_darcs" ]; then
        darcs pull --all
# svk
elif [ -n "`grep $HERE ~/.svk/config`" ]; then
    svk up
# perforce
#   todo
# arch
#   todo
fi

tracd debian init script

tracd init script on debian stable. consists of two parts, /etc/init.d/tracd and /etc/default/tracd

This is /etc/init.d/tracd

#! /bin/sh
#
# tracd           Trac standalone server daemon
#
# Author: cocoaberry
#

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Trac standalone server"
NAME=tracd
DAEMON=/usr/bin/$NAME
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

# defaults for tracd
TRACD_PORT=8080
TRACD_BIND_ADDRESS=0.0.0.0
TRACD_EXTRA_OPTS=

# Read config file if it is present.
if [ -r /etc/default/$NAME ]
then
        . /etc/default/$NAME
fi

#
# Function that starts the daemon/service.
#
d_start() {
        start-stop-daemon --start --background --make-pidfile --quiet \
                --pidfile $PIDFILE --chuid $TRACD_USER \
                --exec $DAEMON -- $TRACD_EXTRA_OPTS --port $TRACD_PORT --hostname $TRACD_BIND_ADDRESS $TRACD_ENVIRONMENTS
}

#
# Function that stops the daemon/service.
#
d_stop() {
        start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE \
                --name $NAME
}

case "$1" in
  start)
        echo -n "Starting $DESC: $NAME"
        d_start
        echo "."
        ;;
  stop)
        echo -n "Stopping $DESC: $NAME"
        d_stop
        echo "."
        ;;
  restart|force-reload)
        #
        # If the "reload" option is implemented, move the "force-reload"
        # option to the "reload" entry above. If not, "force-reload" is
        # just the same as "restart".
        #
        echo -n "Restarting $DESC: $NAME"
        d_stop
        sleep 1
        d_start
        echo "."
        ;;
  *)
        echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0



This is /etc/default/tracd

# Default settings for tracd. This file is sourced by
# /etc/init.d/tracd

# MAJOR HACK - disable globbing so $TRACD_EXTRA_OPTS on cmdline won't expand
# the *
set -f
# The user that tracd runs as
TRACD_USER=tracd
# The environments that tracd manages. If more than one, separate
# with spaces
TRACD_ENVIRONMENTS=/home/tracd/trac-env
# Extra options to tracd
TRACD_EXTRA_OPTS="--auth *,/home/tracd/trac.htdigest,TracRealm"
# The port that tracd binds to. The default is 8080
# TRACD_PORT=8080
# The addresses that tracd binds to. The default is 0.0.0.0
# TRACD_BIND_ADDRESS=0.0.0.0

create a rails app from rails trunk, optionally committing to a subversion repository

I name this script railstrunk on my machine. So, usage would be:

railstrunk app_name


That creates a rails application under app_name.

If app_name is a subversion working copy, rails is set as an external and generated files are committed, and some ignore properties are set.

Here's how I'd go about creating a versioned rails app:

mkdir -p happy_app happy_app/trunk happy_app/tags happy_app/branches 
svn import happy_app http://myserver/myrepos/happy_app -m "Layout for happy_app"
rm -rf happy_app
svn co http://myserver/myrepos/happy_app/trunk happy_app
railstrunk happy_app


$rails_dir is set at the beginning of script, and it should be a path to a working copy of rails trunk on your machine. It's merely used to speed things up, it's not necessary.

Notice I remove the silly public/index.html from the generated app.

And now the code:

#!/bin/bash

rails_dir=~/code/ruby/rails

if [ $# != 1 ]; then
  echo "Usage: $0 app_name"
  echo
  echo "Creates a rails application under app_name."
  echo
  echo "If app_name is a subversion working copy, rails is set as an external"
  echo "and generated files are committed."
  echo
  echo "If $rails_dir exists, things are sped up by either symlinking it"
  echo "(for non-versioned apps) or copying it to the vendor dir."
  echo
  echo "$rails_dir should be a rails trunk working copy."
  exit
fi

dir=$1
mkdir -p $dir
cd $dir

if [ -n "`ls`" ]; then
  echo "Can't create app: $dir is not empty." >&2
  exit 1
fi

if [ -d $rails_dir ]; then
  if [ "`svn info $rails_dir 2>/dev/null | grep URL:`" != "URL: http://dev.rubyonrails.org/svn/rails/trunk" ]; then
    echo "$rails_dir is not a rails trunk working copy. Not going to use it." >&2
  elif [ -n "`svn st $rails_dir`" ]; then
    echo "$rails_dir is modified. Not going to use it." >&2
  else
    use_rails_dir=1
  fi
fi

if [ -z "`svn info 2>/dev/null`" ]; then
  mkdir vendor
  if [ -n "$use_rails_dir" ]; then
    ln -s $rails_dir vendor/rails
    cd vendor/rails
    svn up
    cd ../..
  else
    svn co http://dev.rubyonrails.org/svn/rails/trunk vendor/rails
  fi
  ruby vendor/rails/railties/bin/rails .
  rm public/index.html
else
  svn mkdir vendor
  svn ps svn:externals 'rails http://dev.rubyonrails.org/svn/rails/trunk' vendor
  svn ci -m 'set rails external to rails trunk'
  [ -n "$use_rails_dir" ] && cp -r $rails_dir vendor/rails
  svn up
  ruby vendor/rails/railties/bin/rails .
  rm public/index.html
  rm log/*
  mv config/database.yml config/database.yml.sample
  svn add . --force
  svn ps svn:ignore '*' tmp/cache tmp/pids tmp/sessions tmp/sockets
  svn ps svn:ignore 'database.yml' config
  svn ps svn:ignore '*.log' log
  svn ci -m "- created rails app
- moved database.yml to database.yml.sample
- deleted public/index.html
- ignored logs and tmp"
  cp config/database.yml.sample config/database.yml
fi

update a working copy and all externals in parallel

If you have an app in subversion with many externals, it may take a bit too long to update it, as updates happen one after another.

This bit of script updates the app and each external in parallel, making it oh so much faster.


#!/usr/local/bin/ruby

puts(
  ( `svn pl -R`.scan(/\S.*'(.*)':\n((?:  .*\n)+)/)\
    .inject({}) { |h, (d, p)| h[d] = p.strip.split(/\s+/); h }\
    .select { |d, ps| ps.include? 'svn:externals' }\
    .map { |xd, ps| [xd, `svn pg svn:externals #{xd}`] }\
    .map { |xd, exts| exts.strip.split(/\s*\n/).map { |l| xd + '/' + l.split(/\s+/).first } }\
    .inject { |a, b| a + b }\
    .map { |d| "cd #{d} && svn up 2>&1" } \
    << 'svn up . --ignore-externals 2>&1'
  )\
  .map { |cmd| [cmd, Thread.new { `#{cmd}` }] }\
  .map { |cmd, thread| "#{cmd}\n#{thread.value}" }.join("\n")
)


(note: if you add an external or change an external property in another way, you'll need to run the standard svn up once)

Shell keepalive script (zsh)

Disclaimer: I do not use this script on TextDrive, due to resource consumption concerns, and would not recommend anyone else doing so without express permission from TPTB.

#!/usr/bin/env zsh

# keepalive
# 
# This is keepalive, a simple zsh script (may be hackable to work for other
# shells) for keeping things running.
# 
# Usage:
# $ keepalive  [command args]
# $ keepalive ssh -N -L 8080:127.0.0.1:8080
# 
# The next three variables can be edited to adjust the action of the script

# If the command dies ${threshold} times in succession without living more
# than ${min_runtime} seconds the script will quit.
local threshold=5
local min_runtime=60

# The script will sleep ${init_sleep_time} seconds after the first failure,
# ${init_sleep_time}*2 after the second, ${init_sleep_time}*4 times after the 
# third, and so on.
local init_sleep_time=5

# ########################### #
# No need to edit below here. #
# ########################### #
local time_started time_ended 
local sleep_time=${init_sleep_time}
local times_until_fail=${threshold}

until (( times_until_fail <= 0 )); do
  time_started=$(date +%s)
  $*
  time_ended=$(date +%s)

  # reset if it's lived longer than ${min_runtime}
  if (( (${time_ended} - ${time_started}) > ${min_runtime} )); then
    times_until_fail=${threshold}
    sleep_time=${init_sleep_time}
  fi

  (( times_until_fail -= 1 ))
 
  echo
  echo "-- $(date +"%d/%m/%y %H:%M:%S"): \`$*\` died!"
  if (( times_until_fail >= 1 )); then
    echo "-- ${times_until_fail} more executions lasting less than ${min_runtime} seconds will result in job failure."
    echo "-- Sleeping ${sleep_time} seconds..."
    echo
    sleep ${sleep_time}
  fi
  
  (( sleep_time *= 2 ))
done

echo "-- Died too many times in too short a space of time. Exiting!"

Find flagged message subjects in maildir

Simple, perhaps slightly cryptic oneliner to get the subjects of all flagged messages in a Maildir. It assumes that 'F' is the flag for flagged messages (as it almost always is) and that your message files end with ":2,".

find ~/Maildir -type f -name "*:2,*F*" -exec egrep -h "^Subject:" "{}" ";" | cut -c 10-

shell/vim .rc's for Japanese support (UTF-8)

Get Japanese (and other multibyte, ascii-unfriendly languages) working in the Terminal.

.inputrc (bash)
set convert-meta off
set meta-flag on
set output-meta on


.cshrc (tcsh)
set dspmbyte=utf8


.vimrc
:set enc=utf-8
:set fenc=utf-8


And don't forget 'ls -w' or 'ls -v' to display files and directories.

Preferences: Uncheck 'Emulation > Escape non-ASCII characters';

More at Apple Support - Topic: Displaying foreign characters in the Terminal command line.

Replacing all shebangs in a rails app

perl -pi -e 's|^#!/.*|#!/usr/bin/env ruby|;' script/* script/*/* public/dispatch.*

Remote FTP transfer with ncftpput

When you can't use SCP…

ncftpput -u username -p password ftpperso.free.fr -R -m /local/path /remote/path

opening in a textmate project all files that match a pattern

This will pass all matched filenames to textmate, generating a project with all files flatly in the drawer (no dirs)

egrep -lr pattern * | grep -v .svn | xargs mate
« Newer Snippets
Older Snippets »
Showing 21-40 of 74 total