Natjo
Natjo

Reputation: 2118

Preserve color running an external command via exec

Is it possible to run an external command in a perl script and preserve the color?

As a simple example, how would I run ls from a perl script and get colored output:

#! /usr/bin/perl

exec "ls";

When I run this, the output is all white, but I would like to preserve the colors, in this example for the directories and executables, etc...

Upvotes: 2

Views: 237

Answers (1)

Dave Cross
Dave Cross

Reputation: 69314

It appears that ls doesn't automatically turn on colours in a subshell.

$ echo `ls`
# Output is uncoloured

We can work around that by using the --color command-line option.

$ echo `ls --color`
# Output is coloured

You can use a similar trick in a subshell that is invoked from Perl.

$ perl -e 'system "ls"'
# Output is uncoloured

$ perl -e 'system "ls --color"'
# Output is coloured.

Upvotes: 3

Related Questions