Some neat aliases, shell functions, and shell one-liners

October 30, 2009

  • Set the command line prompt to the current shell level and directory (directory is abbreviated if very long)
    chdir () 
    { 
        if [ $# -eq 2 ]; then
            'cd' `pwd | sed -e "s@$1@$2@"`;
        else
            'cd' "$@";
        fi && {
             if [ "${PWD#/*/*/}" = "$PWD" ]; then
                PS1='[${SHLVL} $PWD] ';
            else
                PS1='[${SHLVL} ..${PWD#${PWD%/*/*}}] ';
            fi;
            case "$TERM" in 
                xterm)
                    echo -ne "33]0;${PWD}07"
                ;;
            esac
        }
    }
    

    Note: add the following alias and environment variable to your $HOME/.profile script:
    alias cd=’chdir’
    SHLVL=0; # for ksh only, also requires ‘(( SHLVL = $SHLVL + 1 ))’ in the ~/.kshrc startup script

  • Pipe the output of a command in to an editor (vi) instead of using more or less.
    function vip
    {
            tmpfile="$HOME/.tmp/$$.vip"
            trap "rm -f $tmpfile" 0 9 15
            cat > $tmpfile
            vi $tmpfile < /dev/tty > /dev/tty 
    }
    

    Note: Requires the $HOME/.tmp directory.
    Example usage: $ ls -l | vip

  • Display the exit code of a program.
    trap "echo ' ' Retcode=\$?" ERR

    Note: Add to your .bashrc or .kshrc startup script

  • List all sub-directories of a specified directory:
    lld () 
    { 
        if [ $# -eq 0 ]; then
            ls -ld */;
        else
            for d in "$@";
            do
                ls -ld ${d:-.}/*/;
            done;
        fi
    }
    

    Example usage:
      $ lsdirs; # display list of subdirectories in the current working directory
      $ lsdirs /usr/local $HOME/logs

  • Copy a directory tree to a remote system:
    $ { cd source_dir; tar cvf - .; } | ssh remote_host '{ cd dest_dir; tar xvf -; }
  • A simplified logfile rolling scheme. Remove all ‘xyz’ log files, except the last $keep files sorted by last modified date. Add to cron for automation.
    $ ls -1t "$logdir/xyz.*.log" | sed -e "1,${keep}d" | xargs -d'\n' rm
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: