Linux – How to disable terminal control escape sequences in Linux

command linelinuxparserterminal

I am writing software that interacts with an embedded device running a version of busybox Linux. Basically, I am just sending commands to the device and parsing the output from the commands . The commands are executed either on the linux shell directly or on the command line of an in-house CLI application running on the device.

Everything works fine except that the output is peppered with terminal control escape sequences. On terminal applications such as teraterm or putty, these escape sequences do useful things like color errors red and other nice features for a pleasant user interface.

The problem is that I have to programmatically parse the output from the commands and account for things like "(esc)[2k" in the output.

For example, a typical send/receive interaction where I send a command, "my-cmd" would go like this…

[send] my-cmd
[receive] my-cmd <esc>[2Kprompt> my-cmd
output of the command
prompt> 

What I would really like to do is to turn off these escape sequences. Is this something that can be done on the command-shell at the beginning of a session? Or is there no way around this other than filtering the output?

Best Answer

Most (if not all) cases where a *nix command prints colored output without the user specifically asking for it with an option involve aliases. In fact, many Linux distributions include an alias for ls and grep specifying colors in the global /etc/bash.bashrc.

These are from my Linux Mint Debian Edition:

$ grep alias /etc/bash.bashrc
    alias ls='ls --color=auto'
    alias grep='grep --colour=auto'

So, if your program is calling these commands through BASH, you are running ls --color=auto instead of ls.

You can bypass aliases in BASH (maybe other shells too but I have not tried it) by the following methods (taken from here):

  1. the full pathname of the command: /bin/ls

  2. command substitution: $(which ls)

  3. the command builtin: command ls

  4. double quotation marks: "ls"

  5. single quotation marks: 'ls'

  6. a backslash character: \ls

If you use one of these methods in your software you should not have to worry about escape sequences.

Related Question