[Linux] Improve your CLI experience: define PS1

You are here:
  • Main
  • Linux
  • [Linux] Improve your CLI experience: define PS1
< All Topics

Hello everybody, 

today we’re going to talk about how to broaden your experience with CLI, to be more specific with variable PS1.

The PS1 defines how your CLI looks like.

For example, check below:

As you can see, my terminal looks very different depending on PS1.

But how can you set a useful PS1?

In PS1 you can do, more or less, 3 different things:

  1. Write something (see the first example, ‘>’)
  2. Write some interpreted command (‘\u’ will return the current username)
  3. Check variables (for example, if you’re an Oracle DBA, you can check your ORACLE_SID exporting in PS1 $ORACLE_SID)

So, let’s start!

Color your prompt

It could be useful to colour the CLI, for example turning red when you’re root or turning green when you’re with your personal user.

In order to do so, you’ve to modify the root’s .bash_profile, adding (or modifying) PS1:

#vi ~/.bash_profile
PS1='\e[31m[\u@\h \W]\$ '

In this way, root’s cli will become as per below:

Then, for your user, if you want to get green, try this:

$ vi ~/.bash_profile 
PS1='\e[32m[\u@\h \W]\$ '

Subsequently, when you become the user, your cli will turn into this:

Getting Variables

Now, suppose that you always need to know a variable’s value, for example ORACLE_SID for Oracle DBA, or your JAVA_HOME.

For doing this, you need to add your variable to your PS1:

$ vi ~/.bash_profile 
PS1='\e[32m($ORACLE_SID)[\u@\h \W]\$ '

See what happens when you modify the variable:

As you can see, the text between parnethesis changes according to ORACLE_SID!

Complex PS1

If you want to get some complex PS1, you can start from this:

$ vi ~/.bash_profile 
PS1='\e[31m($ORACLE_SID)\e[32m[\u@\h \W]\$ \e[0;37m'

In this way, you will have a red ORACLE_SID, a green info about user, hostname and current directory and white text for command and output:

You can even define some functions that you can call inside your PS1:

$ vi ~/.bash_profile 
function free_cpu(){
top -n 1 | head -3| tail -1 | awk '{print $8}'
 function free_mem(){
 free -h | grep Mem | awk '{print $4}'
PS1='\e[31m[$(free_mem) $(free_cpu)%]\e[32m[\u@\h \W]\$ \e[0;37m'

In this way, every time that you hit Enter, you will check status of ram and cpu:

That’s it, now you can build your complex PS1, with a lot of colours and information!


Table of Contents