Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the directory in which a running Haskell script or application lives?

I have a Haskell script that runs via a shebang line making use of the runhaskell utility. E.g...

#! /usr/bin/env runhaskell
module Main where
main = do { ... }

Now, I'd like to be able to determine the directory in which that script resides from within the script, itself. So, if the script lives in /home/me/my-haskell-app/script.hs, I should be able to run it from anywhere, using a relative or absolute path, and it should know it's located in the /home/me/my-haskell-app/ directory.

I thought the functionality available in the System.Environment module might be able to help, but it fell a little short. getProgName did not seem to provide useful file-path information. I found that the environment variable _ (that's an underscore) would sometimes contain the path to the script, as it was invoked; however, as soon as the script is invoked via some other program or parent script, that environment variable seems to lose its value (and I am needing to invoke my Haskell script from another, parent application).

Also useful-to-know would be whether I can determine the directory in which a pre-compiled Haskell executable lives, using the same technique or otherwise.

like image 847
Chris W. Avatar asked Jul 26 '10 18:07

Chris W.


1 Answers

For compiled executables, In GHC 7.6 or later you can use System.Environment.getExecutablePath.

getExecutablePath :: IO FilePathSource

  Returns the absolute pathname of the current executable.
  Note that for scripts and interactive sessions, this is the path to the
  interpreter (e.g. ghci.) 
like image 166
cheecheeo Avatar answered Oct 31 '22 14:10

cheecheeo