Snippets

 

A collection of snippets I’m using sometimes but my brain refuses to remember ..

Linux

Create *nix timestamp

date --utc --date "2011-11-11 11:11:11" +%s

Convert screencast video

mencoder -idx input.ogv -ovc lavc -oac mp3lame -o output

bash/zsh use cursor up/down keys for command history up/down

bindkey "^[[A" history-search-backward
bindkey "^[[B" history-search-forward

TrueCrypt GUIless/console mount encrypted volume

sudo truecrypt -t -k "" --protect-hidden=no /path/to/encfile /path/to/mountpoint

Find out which application runs on a given port and protocol

sudo fuser -n tcp 8080

List your hardware

sudo lshw

Directory tree comparison

diff -r dir1 dir2

Backup directory using rsync with progress bar

rsync -h --progress --stats -r -tgo -l -p -D --update --delete-after /path/to/dir-to-be-saved /path/to/targetdir/

Tell SVN not to store your password in .svn ..

svn command --no-auth-cache

Execute function on shell script exit

#!/bin/sh
# exit function
onExit() {
   # do something here .. cleanup etc ....
}
# bind exit function
trap onExit ERR EXIT
 
# here's the normal code to be executed

Curl send header

curl -H "headername:value" url
 
e.g. curl -H "REMOTE_USER:foo" http://developers.android.com

Curl send POST request

curl -X POST url
 
e.g. curl -X POST http://developers.android.com

Curl get all response headers

curl -i url
 
e.g. curl -i http://developers.android.com

SQL

Partially anonymize e-mail addresses

UPDATE <TABLE_NAME>
SET <EMAIL_FIELD>=
  INSERT(
    <EMAIL_FIELD>,
    POSITION('@' IN <EMAIL_FIELD>),
    100,
    CONCAT(FLOOR(1 + (RAND() * 100)),'@hascode.com'))
  WHERE
    POSITION('@' IN <EMAIL_FIELD>)>0;

Find duplicate entries

SELECT COUNT(*), <FIELDNAME> FROM <TABLENAME>
GROUP BY <FIELDNAME>
HAVING COUNT(*)>1;

Postgres create roles

CREATE ROLE name;
DROP ROLE name;
SELECT rolname FROM pg_roles;
\du
GRANT name TO username

Postgres set user password

ALTER USER
ALTER USER root WITH password 'xxx';

Postgres change database

\cDBNAME

Java

Show processes

jps

Create heap dump from running process

jmap -dump:format=b,file=/tmp/heap.bin 2381

Create heap dump on OutOfMemoryError

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/save/dumps

Screen detach session/ list  / reattach

Detach: Ctrl + A + D

List:

$ screen -ls
There is a screen on:
    2859.pts-0.host    (11/07/11 20:18:00)    (Detached)
1 Socket in /var/run/screen/S-user.

Reattach:

screen -r 2859.pts-0.host

Apache Webserver

Deny all methods excepting POST and GET

RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD)
RewriteRule .* - [F]

Rewrite all aliases for a domain to a single domain

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain1\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain2\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain3\.com [NC,OR]
RewriteRule (.*) http://mydomain.com/$1 [R=301,L]