Hack 42. Use bash shell function inside PS1 variable

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

ramesh@dev-db ~> function httpdcount {
>  ps aux | grep httpd | grep -v grep | wc -l
> }

ramesh@dev-db ~> export PS1="\u@\h [`httpdcount`]> "

ramesh@dev-db [12]>

[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:

$ vi .bash_profile
function httpdcount {
  ps aux | grep httpd | grep -v grep | wc -l
}
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.

Comments on this entry are closed.