Get SSH one-liner commands to show color

I'd like to enable colored text output on SSH one-liner commands, but I can't seem to get it to work on OS X, Ubuntu 14.10, or OpenSUSE 12.2.

If I ssh into a server and type, say, ls --color=auto in the prompt, it works just fine, showing directories, symlinks, and regular files in different colors, however, if I put the command in an ssh one-liner on the same system: ssh user@host "ls --color=auto", the output isn't colored.

Typing echo $TERM gives me xterm-256color whether or not I put it in a one-liner statement.

This is mainly for color-coding errors and warnings on remote builds, but it would be nice to get it enabled for everything.

Any advice?


Solution 1:

ssh user@host "ls --color=auto"

ls only outputs colors when it is writing to a terminal. When you specify a command for ssh to run on the remote host, ssh doesn't allocate a TTY (terminal interface) by default. So, when you run the above command, ssh doesn't allocate a terminal on the remote system, ls sees it's not writing to a terminal, and it doesn't output colors.

You can run ssh with the -t option to make it allocate a terminal. The following should print colors:

ssh -t user@host "ls --color=auto"

If ssh is being run non-interactively, and is own local output isn't going to a terminal, then it will ignore a single -t flag. In this case, you can specify -t more than once to force ssh to allocate a TTY on the remote system:

ssh -tt user@host "ls --color=auto"