Make ls distinguish scripts from binaries in output

binarycatlsscripting

Is it possible to make ls distinguish executable scripts from actual compiled binaries?

The permissions are most often the same (+x), and with ls -F you get an asterisk suffix (*) for both, so it's hard to tell them apart. I have a script to setup the colors of ls, but it relies on the file being executable or not, so they show up the same:

BG='01;32'  # green
EX="ex=$BG" # file with execute permission

I don't want to depend on the extension as so many of these files don't have it.

I want this so when I see some bizarre error message and think, "What code caused that?", I know whether or not it's safe to cat the file.

If there is no standard solution, what about parsing the output of file, in one common function, and inserting some distinctive mark? Or would that be much too slow for ls?

Best Answer

You need to look at the contents of a file to distinguish between binaries and scripts. ls won't do this, it only looks at file names and metadata (type, permission, etc.).

Here's a crude parser for file that colors scripts and binaries differently. It acts like ls -d; adding metadata would require a patch-up job that calls for a more direct approach (e.g. in Perl or Python); use lsx somedir/* to list the contents of a directory. File names are assumed not to contain newlines nor colons (you can change the : separator for some other string with the -F option to file).

lsx () {
  file -iN -- "$@" |
  while IFS= read -r line; do
    name=${line%%: *}; type=${line#*: }
    color=0
    case $type in
      application/x-executable*) color='32';;
      text/x-shellscript*) color='01;32';;
      application/*zip*) color='31';;
    esac
    printf '\033[%sm%s\033[0m\n' "$color" "$name"
  done
}
Related Question