Linux: get absolute path of running shell script / executable

Q. In Linux from a running shell script or a C/C++ executable how to get the absolute path of itself?

Ans:

For shell script:
Below line will give you the absolute path of shell script that is running.

ABSOLUTE_DIR_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

For a c/c++ executable:

void
getExecutableAbsolutePath(
    IN std::string &path
    )
{
    char linkname[1024];
    ssize_t r;

    r = readlink("/proc/self/exe", linkname, 1024);
    assert(-1 != r);
    linkname[r] = '\0';
    path = linkname;
    std::size_t found = path.find_last_of("/");
    path = path.substr(0, found+1);
}

 

 

Advertisements