The Linux Page

Extending "less"

Endless Pier, Endless Possibilities with less

Adding More Support for Binaries

The less tool does a lot more than just show plain text files now a day.

This is done by piping the output of one or more commands run against the input, instead of directly showing said file contents.

The extension works through a set of variables named LESSOPEN and LESSCLOSE.

The LESSOPEN has a pipe at the start, end the name "lesspipe" for the script doing the heavy lifting:

| /usr/bin/lesspipe %s

The idea is for that script to write the results you want less to display to stdout.

So for example that script could do:

echo "Blah!"

and less would show "Blah!" instead of the contents of the input file.

On my end, I found out that ELF files were not handled. Since I like to do objdump -x ... a lot to see things such as the list of .so that the binary is linked against, I thought I'd add it to my alex-tools.

The script I wrote is as follow, it is saved under ~/.lessfilter:

#!/bin/bash -e
MIME=`file --brief --mime-type "$1"`
case "${MIME}" in
"application/x-sharedlib")
        objdump -x $1
        exit 0
        ;;

esac

exit 1

I use `file ...` to detect the file type and save it in the MIME variable. Use that output to determine which file I want to handle. In this case, I get "application/x-sharedlib" (which is wierd since I tested that against an executable, not a .so file). As we can see, all we have to do is execute one command. In my case, the objdump -x ... command.

Now you can easily extend that one script to handle any number of files and make it really easy on you to see binary files without having to remember all the command line options.

Output Based on Filename

One funny trick, you can hijack a filename like so:

if test "`basename $1`" = "firewall"
then
        sudo iptables -L -nvx
        exit 0
fi

You'll notice that less (?!) asks you for your sudo password and then you see the iptables rules displayed on your screen. The only glitch here is that a file named firewall needs to exist and it can be really confusing if you get the iptables output instead of your firewall script... so be careful with such!