Skip to content

Instantly share code, notes, and snippets.

@earonesty
Last active Mar 7, 2019
Embed
What would you like to do?
ls --color support for systems that don't have it, like AIX, and when you don't want to install gnu
#!/usr/bin/perl
use strict;
use Getopt::Long qw(:config pass_through no_ignore_case bundling);
my $do_color;
GetOptions("colors"=>\$do_color);
my @buf;
my $do_cols;
my $cur_col;
my $max_len;
my $num_cols;
my $screen_width;
my $cur_len;
if (!$do_color) {
exec("ls", @ARGV);
} else {
my ($do_long);
GetOptions("l"=>\$do_long);
if ($do_long) {
unshift @ARGV, "-l";
} elsif (-t STDOUT) {
$do_cols=1;
$screen_width=`tput cols`; chomp $screen_width;
}
for (@ARGV) {
s/\"/\\\"/g;
$_="\"$_\"";
}
open(I,"ls @ARGV|");
while(<I>) {
chomp;
my $type;
if (!$do_long) {
$type = 'x' if -x $_;
$type = 'd' if -d $_;
$type = 'l' if -l $_;
$type = 's' if -k $_;
} else {
$type = $1 if /^(.)/;
$type = 'x' if $type eq '-' && (/^...x/ || /^......x/ || /^.........x/);
}
if ($do_cols>0) {
if ($do_cols==2) {
print_col();
} else {
push @buf, [$type, $_];
if (length($_) > $max_len) {
$max_len = length($_);
}
if (@buf > 1000) {
print_buf();
}
}
} else {
print colorize($type, $_), "\n";
}
}
if ($screen_width > 0) {
print_buf();
if ($cur_col) {
print "\n";
}
}
}
sub print_col {
my ($type, $str) = @_;
my $padding = " " x ((($max_len+1)*$cur_col) - $cur_len);
print $padding;
$cur_len+=(length($str)+length($padding));
print colorize($type, $str);
if ($cur_col==($num_cols-1)) {
print "\n";
$cur_col=0;
$cur_len=0;
} else {
++$cur_col;
}
}
sub print_buf {
$num_cols = int($screen_width/($max_len+2));
for (@buf) {
print_col(@$_);
}
$do_cols=2;
@buf=();
}
sub colorize {
my ($type, $str) = @_;
($type eq 'd') and ($str="\033[1;34m$str\033[0m");
($type eq 'l') and ($str="\033[1;36m$str\033[0m");
($type eq 's') and ($str="\033[1;31m$str\033[0m");
($type eq 'x') and ($str="\033[1;32m$str\033[0m");
$str="\033[0m$str";
return $str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment