Hack 43. Use shell script inside PS1 variable

by Ramesh

You can also invoke a shell script inside the PS1 variable. In the example below, the ~/bin/totalfilesize.sh, which calculates the total filesize of the current directory, is invoked inside the PS1 variable.

  1. ramesh@dev-db ~> cat ~/bin/totalfilesize.sh
  2.  
  3. for filesize in $(ls -l . | grep "^-" | awk '{print $5}')
  4. do
  5. let totalsize=$totalsize+$filesize
  6. done
  7. echo -n "$totalsize"
  8.  
  9. ramesh@dev-db ~> export PATH=$PATH:~/bin
  10.  
  11. ramesh@dev-db ~> export PS1="\u@\h [\$(totalfilesize.sh) bytes]> "
  12.  
  13. ramesh@dev-db [534 bytes]> cd /etc/mail
  14.  
  15. ramesh@dev-db [167997 bytes]>

[Note: This executes the totalfilesize.sh to display the total file size of the current directory in the PS1 prompt]

You can also write the ~/bin/totalfilesize.sh as shown below without the for loop.

  1. ramesh@dev-db ~> cat ~/bin/totalfilesize.sh
  2.  
  3. ls -l | awk '/^-/ { sum+=$5 } END { printf sum }'