Thursday 7 February 2013

Bashrc Tips

Some ~/.bashrc tips that include a bash prompt design, a bash function called lst that lists the most recently modified directory entries, aliases p and lsd to navigate directories, and lss alias to sort directory entries according to size in human-readable format. Tested in Debian GNU/Linux 6.
  • bash prompt:
    
    PS1="\$(return_value=\$?;if [ \$return_value != 0 ]; then echo -e \"\e[1m\e[31m\$return_value\e[0m\"; fi)\[\e[1m\]\u@\h:\w-\t\[\e[0m\]\n\$ "
    
    Results in a white, bold text, consisting of username, hostname, current working directory and the current local time. It may be prefixed by a non-zero return value of the previous command in bold red.
  • lst function that displays a list of 10 (the default) most recently modified entries (current directory by default) without the total line in output:
    
    lst ()
    {
        case $1 in
            +*)
                _lines=-`echo $1 | cut -c2-`;
                shift
            ;;
        esac;
        if [ -z "$1" ] ;then
            echo -e "$PWD:\n";ls -lhAt --color "$PWD" | sed '/^total/d' | head $_lines ;echo
        else
            for dir in "$@"; do echo -e "$dir:\n";ls -lhAt --color "$dir" | sed '/^total/d' | head $_lines ;echo; done
        fi
    }
    
    Note: The number of entries should be the first argument if specified, and it is prefixed with the plus symbol. Once changed, the number of entries listed remains the default until changed again. Usage examples:
    
    lst
    lst +15
    lst /path/to/dir
    lst /path/to/dir1 /path/to/dir2
    lst +5 /path/to/dir1 /path/to/dir2
    
  • lst function with the total line in output:
    
    _lines=10
    lst ()
    {
        case $1 in
            +*)
                _lines=`echo $1 | cut -c2-`;
                shift
            ;;
        esac;
        if [ -z "$1" ] ;then
            echo -e "$PWD:\n";ls -lhAt --color "$PWD" | head -$(($_lines+1)) ;echo
        else
            for dir in "$@"; do echo -e "$dir:\n";ls -lhAt --color "$dir" | head -$(($_lines+1)) ;echo; done
        fi
    }
    
  • aliases:
    
    alias p=pushd
    alias lsd='dirs -v'
    alias lss='du -hsx * | sort -rh | less'
    alias less='less -RFX'
    
    Usage examples:
    
    p /var/log # change current working directory to /var/log, now top of the directory stack
    p /etc     # change current working directory to /etc, now top of the directory stack
    lsd        # to see the directory stack
    p +5       # switch to the fifth directory in the directory stack
    p          # bounce between the two most recently switched to directories.
    
  • References:
    help pushd
    lss
    lst, lsd, p
    less -FX