'sh equivalent of __FILE__

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



Solution 1:[1]

Try using $0.

Solution 2:[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__

Solution 3:[3]

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lhf
Solution 2 Oliver Williams
Solution 3 Community
Solution 4