Hack 43. Use shell script inside PS1 variable

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.

ramesh@dev-db ~> cat ~/bin/totalfilesize.sh

for filesize in $(ls -l . | grep "^-" | awk '{print $5}')
  let totalsize=$totalsize+$filesize
echo -n "$totalsize"

ramesh@dev-db ~> export PATH=$PATH:~/bin

ramesh@dev-db ~> export PS1="\u@\h [\$(totalfilesize.sh) bytes]> "

ramesh@dev-db [534 bytes]> cd /etc/mail

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.

ramesh@dev-db ~> cat ~/bin/totalfilesize.sh

ls -l | awk '/^-/ { sum+=$5 } END { printf sum }'

Comments on this entry are closed.