I feel stupid -- determine the full path to a file

Dave Smith dave at thesmithfam.org
Thu Dec 6 13:12:51 MST 2007


Michael L Torrie wrote:
> I have a script that is passed a filename.  This filename could be
> absolute, it could be relative.  I need the script to be able to
> determine the pull path to this file.  I've read lots of hacks for doing
> this that involve ls, find, and pwd, but none of them do what I need.
> If the script was invoked like this,
>
> Any tips?
>   

C has a function called realpath() that does the job, but bash has no 
such counterpart. I  usually end up building my own little binary to do 
it, and calling that from my shell scripts. Here's the source:


#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

/**
 * Converts a directory or file name to its canonicalized representation
 * using the realpath() function (man realpath).
 */
int main( int argc, char **argv )
{
    if( argc != 2 )
    {
        printf( "Usage: %s <path>\n", argv[0] );
        return 1;
    }

    char output[PATH_MAX];
    realpath( argv[1], output );
    printf( "%s\n", output );

    return 0;
}



More information about the PLUG mailing list