7

Is there a sh equivalent of __FILE__, to give me the pathname of the currently executing file? POSIX solutions preferred, bash acceptable, thanks.

quickshiftin
  • 60,711
  • 9
  • 63
  • 83
pilcrow
  • 54,181
  • 12
  • 87
  • 133
  • possible duplicate of [Can a Bash script tell what directory it's stored in?](http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in) –  Mar 20 '15 at 09:09

4 Answers4

5

Try using $0.

lhf
  • 67,570
  • 9
  • 102
  • 136
  • 4
    This is not equivalent to `__FILE__` if you are doing it in a file that is sourced from another file. – mxcl Aug 15 '12 at 14:20
2

This will grab both the file and the directory

# !/bin/sh

# store where we are
__PWD__=$(pwd)
# go to the current file (i.e. this file)
cd $(dirname $0)
# gives the file name, __FILE__
echo $0
__FILE__=$0
# gives the directory name, __DIR__
echo $(dirname $0)
__DIR__=$(dirname $0)
# this has been a test of the Linux filesystem; we now return you to your previous program.. :)
cd $__PWD__
Oliver Williams
  • 5,132
  • 5
  • 31
  • 66
1

For a bash script solution

Getting the source directory of a Bash script from within

Community
  • 1
  • 1
karlphillip
  • 89,883
  • 35
  • 240
  • 408
0

Just a thought:

#!/usr/bin/env bash

# "$0" will expand to the name of the script, as called from the command line
readlink -f $0
miku
  • 172,072
  • 46
  • 300
  • 307
  • That will be incorrect if the script is called via the $PATH variable. – Bill Lynch Jul 23 '10 at 14:26
  • Note that `readlink` isn't entirely portable. OSX (and presumably BSD in general?) have a completely different version - where `-f` isn't supported. Rather, where `-f` means something different (and not helpful here). – Telemachus Jul 23 '10 at 14:29
  • `echo $(readlink -f $0)` works fine on OSX 10.6, just tested it. – miku Jul 23 '10 at 14:30
  • 1
    Why are you using `echo`. Doesn't `readlink -f $0` by itself work? – Dennis Williamson Jul 23 '10 at 14:43
  • @The MYYN You must have gnu's `coreutils` installed without the `g` prefixes. Here's what happens when I run that command: `readlink: illegal option -- f` (Yes, I'm on 10.6. I actually have gnu's `readlink` as well, but only under the alias `greadlink`. http://pastie.org/1057557 for an example.) – Telemachus Jul 23 '10 at 20:29