Hack 42. Use bash shell function inside PS1 variable

by Ramesh

You can also invoke a bash shell function in the PS1 as shown below.

  1. ramesh@dev-db ~> function httpdcount {
  2. > ps aux | grep httpd | grep -v grep | wc -l
  3. > }
  4.  
  5. ramesh@dev-db ~> export PS1="\u@\h [`httpdcount`]> "
  6.  
  7. ramesh@dev-db [12]>
  8.  

[Note: This displays the total number of running httpd processes]

You can add the following line to your ~/.bash_profile or ~/.bashrc to make this change permanent:

  1. $ vi .bash_profile
  2. function httpdcount {
  3. ps aux | grep httpd | grep -v grep | wc -l
  4. }
  5. export PS1='\u@\h [`httpdcount`]> '

Note: You can also use “pgrep httpd | wc –l” instead of the “ps aux | grep httpd | grep -v grep | wc –l” in the above httpdcount function.