This blog has permanently moved to

Contact Form | Email Address

© 2018 All rights reserved by Boseji

Thank you for all your support.

Sunday, March 10, 2013

Fancy Command Prompt: Linux in Style

We wondered if the Linux prompt can be more snazzier that we have it by default dull type.
To something more interesting:
This magic is using the 'PS1' environment variable in Linux.
Here is the command that does this magic:
PS1="\n\[\033[1;37m\]\342\224\214($(if [[ ${EUID} == 0 ]]; then echo '\[\033[01;31m\]\h'; else echo '\[\033[01;34m\]\u@\h'; fi)\[\033[1;37m\])\342\224\200(\[\033[1;34m\]\$?\[\033[1;37m\])\342\224\200(\[\033[1;34m\]\@ \d\[\033[1;37m\])\[\033[1;37m\]\342\224\200(\[\033[1;32m\]\w\[\033[1;37m\])\342\224\200(\[\033[1;32m\]\$(ls -1 | wc -l | sed 's: ::g') files, \$(ls -lah | grep -m 1 total | sed 's/total //')b\[\033[1;37m\])\n\342\224\224\342\206\222> \[\033[0m\]"

There are 3 parts to this magic:
  1. Usage of Special Unicode characters:
    Looking at the beginning of the line you might have noticed the char '┌' which is U+0x250C. This is a UNICODE character to make top left border. In order to find the right string to code the PS1 variable you would need to the octal codes for the special char. To get that we have these commands:
    • If you know the code of the char:
      echo -e "\u250C" | hexdump -v -e '/1 "%03o "' | awk '{print "\\" $1 "\\" $2 "\\" $3 }'
      This is for the top left border char that we are talking here. It would print:
      This is the code you can now use in the PS1 variable definition.
    • In case you know the char it self then:
      echo ┌ | hexdump -v -e '/1 "%03o "' | awk '{print "\\" $1 "\\" $2 "\\" $3 }'
      This gives you the codes again in the same manner as the earlier one.

    In order to get further info you can visit the following links:
    http://www.unicode.org/charts/ - Here you get all the charts for Unicode characters
  2. Special formatting for the normal user and the root user:
    The piece of the variable that does this job is -
    ($(if [[ ${EUID} == 0 ]]; then echo '\[\033[01;31m\]\h'; else echo '\[\033[01;34m\]\u@\h'; fi)
    This would ensure that if the user is root the only the host is printed else the user name @ host is printed.
  3. Finding the Number of Files and the total size:
    This part is done in two folds -
    First part is the number of files that exist in the current working directory:
    \$(ls -1 | wc -l | sed 's: ::g') files,
    The next part is the total size of all files under the directory(no including sub-directory sizes):
    \$(ls -lah | grep -m 1 total | sed 's/total //')b
This make a nice way to work on Linux with style. The possibilities are only limited by your imagination and few time.
Inspired by the Archlinux wiki: https://wiki.archlinux.org/index.php/Color_Bash_Prompt

    No comments:

    Post a Comment