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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s