I've got 'color cat' working nicely, thanks to others
(see How can i colorize cat output including unknown filetypes in b&w?).
In my .bashrc
:
cdc() {
for fn in "$@"; do
source-highlight --out-format=esc -o STDOUT -i $fn 2>/dev/null || /bin/cat $fn;
done
}
alias cat='cdc' # To be next to the cdc definition above.
I'd like to be able to use this technique for other functions like head, tail and less.
How could I do that for all four functions? Any way to generalize the answer?
I have an option for gd
doing git diff
using
gd() {
git diff -r --color=always "$@"
}
Best Answer
Something like this should do what you want:
You can condense it like this:
Example
With the above in a shell script, called
tst_ccmds.bash
.When I run this, I get the functions set as you'd asked for:
In action
When I use these functions in my shell (
source ./tst_ccmds.bash
) they work as follows:cat
head
tail
plain text
What's the trick?
The biggest trick, and I would call it more of a hack, is the use of a dash (
-
) as an argument tocat
,head
, andtail
through a pipe which forces them to output the content that came fromsource-highlight
through STDIN of the pipe. This bit:The other trick is using the
--failsafe
option ofsource-highlight
:This means that if a language definition is not found, it acts like
cat
, simply copying its input to the standard output.Note about aliases
This function will fail if any of
head
,tail
orcat
are aliases because the result of thetype
call will not point to the executable. If you need to use this function with an alias (for example, if you want to useless
which requires the-R
flag to colorize) you will have to delete the alias and add the aliased command separately: