Search code examples
regexlinuxterminalpromptansi-escape

Handling colored bash prompt


I have an adapter code which executes some specific commands on a Linux machine via SSH. It executes commands and handles the output of each command in a specified manner.

The issue being faced is very straightforward.

I am connecting to a Bash prompt that uses colors. Here are the details of the PS1 variable:

PS1="\[\033[1;34m\][\$(date +%H%M)][\u@\h:\w]$\[^[[0m}\]"

The code uses regex which decides a valid terminal first and then proceeds with the commands.

For example, .*\$ is considered valid

I can't seem to handle [^[[0m} properly and code is not able to identify the terminal as a valid one. If I remove it from PS1 variable, things work fine.

Can anyone please suggest what regular expressions might be entered so that the code takes it as a valid terminal?


Solution

  • I think the PS1 variable you provided above is broken.

    I ran the following experiment in my terminal window:

    [guest@localhost ~] $ export PS1="\\[\033[1;34m\\][\$(date +%H%M)][\u@\h:\w]$\\[^[[0m}\\]"
    
    [2137][guest@localhost:~]$^[[0m}
    

    As you can see ^[[0m} is not interpreted properly. I assume it is the end of the color in the prompt. I think it should be \\[\033[0m\\].

    Here is the whole PS1 variable:

    PS1="\\[\033[1;34m\\][\$(date +%H%M)][\u@\h:\w]$\\[\033[0m\\]"
    

    After testing it you get this:

    [2137][guest@localhost:~]$^[[0m}export PS1="\\[\033[1;34m\\][\$(date +%H%M)][\u@\h:\w]$\\[\033[0m\\]"
    
    [2139][guest@localhost:~]$