Check if executable is valid Check if executable is valid unix unix

Check if executable is valid


The function that allows you to check whether a file is executable or not is Unix.access. If you want to additionally search the path, you'll need additional scaffolding, e.g.:

let syspath = String.split_on_char ':' (Sys.getenv "PATH")let check_executable path =  let open Unix in  try    access path [ X_OK ]; Some path  with _ -> Nonelet starts_with s prefix =  let open String in  let plen = length prefix in  length s >= plen && sub s 0 plen = prefixlet search_path name =  if starts_with name "/" || starts_with name "./" || starts_with name "../"  then    check_executable name  else    List.fold_left (fun acc dir ->      match acc with      | Some file -> Some file      | None ->        check_executable (Filename.concat dir name)    ) None syspathlet main () =  Array.iter (fun arg ->    match search_path arg with    | None -> Printf.printf "%s (Not found)\n" arg    | Some file -> Printf.printf "%s -> %s\n" arg file)  Array.(sub Sys.argv 1 (length Sys.argv - 1))let () = main ()


You can use the file command for this purpose. file returns this for an executable:

file /bin/lsoutput => ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0x37cdd635587f519989044055623abff939002027, stripped

You can either parse the output or use one of many command line options that file command has.


In addition to codeforester's answer of using file, there are also bindings to libmagic which effectively gives you access to file's output without the need to shell out. See https://github.com/Chris00/ocaml-magic, available in opam as magic.