useful script and code snippets

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
evilbeanfiend
Posts: 2650
Joined: Tue Mar 13, 2007 7:05 am UTC
Location: the old world

useful script and code snippets

Postby evilbeanfiend » Fri Feb 29, 2008 2:17 pm UTC

you probably have something interesting in your .bashrc or .emacs or perhpas have some neat little bit of python or c++.
share it here!

i've just added this to my .bashrc

Code: Select all

function search {
   find $1 -exec grep -H -n "$2" '{}' \;
}
in ur beanz makin u eveel

User avatar
bridge
Posts: 195
Joined: Sun Feb 03, 2008 2:24 pm UTC
Location: Zurich < x < Rome

Re: useful script and code snippets

Postby bridge » Fri Feb 29, 2008 9:18 pm UTC

Code: Select all

export PS1="\033[34;1m[\033[31;1m\u\033[34;1m@\033[35;1m\H\033[34;1m:\033[33;1m\w\033[34;1m] [\033[30;1m\t\033[34;1m]\033[0m\n$"

looks more or less like that
myshell wrote:[bridge@Tijuana.local:~/Desktop] [22:09:12]
$ echo helloxkcd
helloxkcd


Essentials:

Code: Select all

alias z='ls -la';
alias q='exit';
Excuse my Super Mario accent

mrkite
Posts: 336
Joined: Tue Sep 04, 2007 8:48 pm UTC

Re: useful script and code snippets

Postby mrkite » Fri Feb 29, 2008 10:54 pm UTC

the only useful snippet I have memorized is:

Code: Select all

#!/usr/bin/perl
while(<>){s/\r\n?/\n/g;print;}


Converts windows and mac text files into unix files.

mrkite
Posts: 336
Joined: Tue Sep 04, 2007 8:48 pm UTC

Re: useful script and code snippets

Postby mrkite » Sat Mar 01, 2008 12:16 am UTC

Ok.. I just wrote another one.

Turn "12345678" into "12,345,678" in javascript:

Code: Select all

num="12345678";
num=num.split('').reverse().join('');
num=num.replace(/(\d{3})(?=\d)/g,"$1,");
num=num.split('').reverse().join('');

User avatar
bridge
Posts: 195
Joined: Sun Feb 03, 2008 2:24 pm UTC
Location: Zurich < x < Rome

Re: useful script and code snippets

Postby bridge » Sat Apr 05, 2008 4:23 pm UTC

Code: Select all

alias timer='xterm -geometry 40x6+10+10 -e "echo \"Press enter to stop\"; time read; echo \"Press enter to close this window\"; read; exit" &'

Opens up a small xterm and waits for you to press enter, when you do it shows the time taken
Useful for measuring quick measurement of execution times of your awemagicsome algorithms :mrgreen:

Any idea on how to grep the output of time?

Code: Select all

time foo | grep real
does not work (it greps the output of foo)
Excuse my Super Mario accent

User avatar
Dropzone
Posts: 405
Joined: Sun Dec 30, 2007 10:12 pm UTC
Location: North Lincs., UK

Re: useful script and code snippets

Postby Dropzone » Sat Apr 05, 2008 5:23 pm UTC

Code: Select all

/bin/time -p foo 2>&1 >/dev/null | grep real

That works, I don't know if there's a neater way to do it.

maafy6
Posts: 102
Joined: Wed Aug 22, 2007 10:43 pm UTC

Re: useful script and code snippets

Postby maafy6 » Sun Apr 06, 2008 6:27 pm UTC

Code: Select all

alias l='ls'
alias s='ls'
alias sl='ls'


I don't know how many times I'll accidentally do this combination:

Code: Select all

[maustin@beeker ~]$ l
bash: l: command not found
[maustin@beeker ~]$ sl
bash: sl: command not found
[maustin@beeker ~]$ s
bash: s: command not found


In the second line, I'll pause for a brief second, forgetting the s that has already been input, then doing the same thing. Also, I refuse to use autocorrect, because it usually becomes far too helpful for its own good.

User avatar
bridge
Posts: 195
Joined: Sun Feb 03, 2008 2:24 pm UTC
Location: Zurich < x < Rome

Re: useful script and code snippets

Postby bridge » Sun Apr 06, 2008 7:39 pm UTC

Thanks for the hint Dropzone

maafy6 wrote:In the second line, I'll pause for a brief second, forgetting the s that has already been input, then doing the same thing...

Nice idea... i should do something that :mrgreen:

Code: Select all

alias mak='make'
alias makw='make'
alias makr='make'
alias mak3='make'
alias mak4='make'
alias makd='make'

btw maafy6:

Code: Select all

alias z='ls -la'
will save you quite a lot of time once you remember use it...
Excuse my Super Mario accent

User avatar
Dingbats
Posts: 921
Joined: Tue Mar 20, 2007 12:46 pm UTC
Location: Sweden
Contact:

Re: useful script and code snippets

Postby Dingbats » Sun Apr 06, 2008 10:05 pm UTC

Code: Select all

alias run='find ~/ -name "$2" | sed "s/^/$1 /g" | bash'

Finds a file/set of files in your home directory and subdirectories of it and runs them with a specified program. So to run all files that end in, say, _suck_cock.mpg with VLC, you'd use:

Code: Select all

run vlc *_suck_cock.mpg


Useful if you don't remember where you put stuff or don't want to cd into a long chain of subdirectories, but on the other hand it's a bit slow sometimes.

EDIT: No, wait, that won't work. You need to put it in a file and execute it as a script of course. :roll:

maafy6
Posts: 102
Joined: Wed Aug 22, 2007 10:43 pm UTC

Re: useful script and code snippets

Postby maafy6 » Mon Apr 07, 2008 2:59 am UTC

bridge wrote:Thanks for the hint Dropzone
btw maafy6:

Code: Select all

alias z='ls -la'
will save you quite a lot of time once you remember use it...


That's already aliased by 'll' :)

I was also recommended to alias rm to trash, where trash is a little script that moves said file into a ~/.trash/<date> directory. This was after I accidentally deleted my local code sandbox. (Fortunately, everything I really needed was checked into svn already and the changes I had made since checkin were still open in a gedit window, but it was still one of those "Oh for f's sake, it's too late on a Friday to do any more work" moments.)

User avatar
ash.gti
Posts: 404
Joined: Thu Feb 07, 2008 1:18 am UTC
Location: Probably a coffee shop.

Re: useful script and code snippets

Postby ash.gti » Mon Apr 07, 2008 3:16 am UTC

I'd have to say

Code: Select all

find . -name “.svn” -print0 | xargs -0 rm -Rf


Is one of the more useful scripts for me...

I check things in and out of SVN's all the time, but get annoyed when I don't need all those hidden subfolders anymore. This is a great help IMO :-P
# drinks WAY to much espresso

coppro
Posts: 117
Joined: Mon Feb 04, 2008 6:04 am UTC

Re: useful script and code snippets

Postby coppro » Mon Apr 07, 2008 4:59 am UTC

maafy6 wrote:
bridge wrote:Thanks for the hint Dropzone
btw maafy6:

Code: Select all

alias z='ls -la'
will save you quite a lot of time once you remember use it...


That's already aliased by 'll' :)
ll is just ls -l. la is ls -a, leading me to add lla=ls -la.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: useful script and code snippets

Postby EvanED » Mon Apr 07, 2008 5:39 pm UTC

maafy6 wrote:That's already aliased by 'll' :)

My 'll' finally unwinds to 'ls -hF --color=auto -Bd -l --si -A" ;-)

(-h prints sizes in human-readable format (e.g. 4.2K) instead of just number of bytes, -F appends * to exes and / to directories (and others), --color=auto turns on colors, -B ignores files ending with ~, -d doesn't list directory contents, -l gives a long listing, --si makes the -h option use 1000 bytes, -A lists ".*" files except ./ and ../.)

One of these days I'll pipe that output into a natural sorting algorithm, but I want to see if I can keep from losing the colors first.

maafy6 wrote:I was also recommended to alias rm to trash, where trash is a little script that moves said file into a ~/.trash/<date> directory.

I've seen someone post on /. a crontab entry that at midnight sets up that alias and at 7am sets rm back to normal. ;-)

I've thought about doing this idea (permanently), but would want to make the trash script work well before I were to do it. In particular, it should be sensitive to mount points. So for instance if you have a partition mounted at /mnt/c/ because you share that drive with Windows or something, and you do:

Code: Select all

/mnt/c/foo# rm *
it shouldn't move everything to ~/.trash because then it has to move data across partitions. This could cause space distribution issues as well as vastly increase the amount of time it takes to "delete" a file. Instead, it should see that the filesystem that it is accessing is mounted at /mnt/c and move it to /mnt/c/trash.

This script is something that I want to write at some point though.

----

EDIT: Here are edited versions of parts of my startup scripts. The most interesting bit is in pathfns-zsh, which I'll put first. I use zsh. If you are good at Bash you can probably adapt them without too much trouble, but they won't work as-is. (The eval lines will need to change
Spoiler:
~/dotfiles/shell/pathfns-zsh:

Code: Select all

# like printenv, except that it splits the output at : and prints them
# on separate lines instead. E.g.:
#  # printpathenv PATH
#  /s/std/bin
#  /usr/lib/qt-3.3/bin
#  /usr/kerberos/bin
#  /usr/local/bin
#  /usr/bin
#  /bin
#  ...
function printpathenv () {
    eval value=\"\$$1\"
    echo "$value" | tr ':' '\n'
    unset value
}


# Lets you edit the specified variable in an editor. Run with, e.g. editpathvar PATH
function editpathvar () {
    local tmp=`~/tmpnam`
    echo "Outputting to $tmp..."
    printpathenv $1 > $tmp
    $EDITOR $tmp
    export $1=`cat $tmp | tr '\n' ':'`
    rm $tmp
}


# these three functions from http://www.prolangs.rutgers.edu/~dufour/linux/files/zshrc
# the comments are mine

# adds the specified value to the beginning or end of the specified colon-separated path variable
#   path_add append VARIABLE ADDITION
#   path_add prepend VARIABLE ADDITION
# e.g. path_add append PATH .
function path_add () {
    eval value=\"\$$2\"
    case "$value" in
        *:$3:*|*:$3|$3:*|$3)
            result="$value"
            ;;
        "")
            export $2
            result="$3"
            ;;
        *)
            case "$1" in
                p*)
                    result="$3:${value}"
                    ;;
                *)
                    result="${value}:$3"
                    ;;
            esac
    esac
    eval $2=$result
    unset result value
}

# wrapper for the above with "append":
#   path_append VARIABLE ADDITION
function path_append () {
    path_add append "$1" "$2"
}

# wrapper for the above with "prepend":
#   path_prepend VARIABLE ADDITION
function path_prepend () {
    path_add prepend "$1" "$2"
}

If you use Bash, the path_append function can look something like this:

Code: Select all

function append() { export $1=${!1}:$2; }
so I suspect you can replace the eval lines with something similar to the ${!1} thing. It's probably possible to write this this concisely in zsh too, but I don't know enough about shell programming. (The Bash version is from a friend of mine (fiddlemath on these forums); the path_add functions are from the given site.)

Less interesting are my aliases:

Code: Select all

alias ls="ls -hF --color=auto"
alias l="ls -Bd"
alias ll="l -l --si -A"

alias grep="grep --color=auto"
alias h="history | grep"

alias dirs="dirs -v"


Even less interesting is my .zshenv:
Spoiler:
~/.zshenv

Code: Select all

# I split off different parts into different files.
# pathfns-zsh defines some useful functions for handling environment variables
#                     that are colon-separated lists of paths.
# options-zsh sets shell options (and some related variables)
# variables-zsh sets environment variables.
#
# options and especially variables I eventually want to replace with a higher level
# description. So variables-zsh uses sh syntax, but I would like to be able to write
# a description of the variables independent of shell syntax, then a translator that
# will convert that to the syntax for whatever shell is being used. I haven't done this yet though.
. ~/dotfiles/shells/pathfns-zsh
. ~/dotfiles/shells/options-zsh
. ~/dotfiles/shells/variables-zsh


# I do this a lot.
function sdl() {
   svn diff $* | less;
}


# Set up case-insensitive tab completion
autoload -U compinit
compinit -C
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'
ZLS_COLORS=$LS_COLORS

# Sets the title of the xterm window to the current command
# From http://forums.macosxhints.com/archive/index.php/t-6493.html
if [[ $TERM == (*xterm*|rxvt|(dt|k|E)term); || $TERM_PROGRAM == Apple_Terminal ]]; then
  precmd () {
    print -Pn "\e]0;%n@%m:%~\a"
  }
  preexec () {
    print -Pn "\e]0;%n@%m:%~ <$1>\a"
  };
fi

# changes the beep to be far less annoying
xset b 40 50 100


And finally my prompt is

Code: Select all

PS1=$'%{\e[0;31m%}%h. %20<...<%~ : %{\e[0m%}'


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 23 guests