Is there a sh equivalent of __FILE__, to give me the pathname of the currently executing file?  POSIX solutions preferred, bash acceptable, thanks.
            Asked
            
        
        
            Active
            
        
            Viewed 2,308 times
        
    7
            
            
         
    
    
        quickshiftin
        
- 66,362
- 10
- 68
- 89
 
    
    
        pilcrow
        
- 56,591
- 13
- 94
- 135
- 
                    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 Answers
5
            Try using $0.
 
    
    
        lhf
        
- 70,581
- 9
- 108
- 149
- 
                    4This 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,966
- 7
- 36
- 78
 
    
    
        user12656390
        
- 21
- 1
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
        
- 181,842
- 47
- 306
- 310
- 
                    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
- 
                    
- 
                    1Why 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
 
    