Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you normalize a file path in Bash?

if you're wanting to chomp part of a filename from the path, "dirname" and "basename" are your friends, and "realpath" is handy too.

dirname /foo/bar/baz 
# /foo/bar 
basename /foo/bar/baz
# baz
dirname $( dirname  /foo/bar/baz  ) 
# /foo 
realpath ../foo
# ../foo: No such file or directory
realpath /tmp/../tmp/../tmp
# /tmp

realpath alternatives

If realpath is not supported by your shell, you can try

readlink -f /path/here/.. 

Also

readlink -m /path/there/../../ 

Works the same as

realpath -s /path/here/../../

in that the path doesn't need to exist to be normalized.


I don't know if there is a direct bash command to do this, but I usually do

normalDir="`cd "${dirToNormalize}";pwd`"
echo "${normalDir}"

and it works well.


Try realpath. Below is the source in its entirety, hereby donated to the public domain.

// realpath.c: display the absolute path to a file or directory.
// Adam Liss, August, 2007
// This program is provided "as-is" to the public domain, without express or
// implied warranty, for any non-profit use, provided this notice is maintained.

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

static char *s_pMyName;
void usage(void);

int main(int argc, char *argv[])
{
    char
        sPath[PATH_MAX];


    s_pMyName = strdup(basename(argv[0]));

    if (argc < 2)
        usage();

    printf("%s\n", realpath(argv[1], sPath));
    return 0;
}    

void usage(void)
{
    fprintf(stderr, "usage: %s PATH\n", s_pMyName);
    exit(1);
}

A portable and reliable solution is to use python, which is preinstalled pretty much everywhere (including Darwin). You have two options:

  1. abspath returns an absolute path but does not resolve symlinks:

    python -c "import os,sys; print(os.path.abspath(sys.argv[1]))" path/to/file

  2. realpath returns an absolute path and in doing so resolves symlinks, generating a canonical path:

    python -c "import os,sys; print(os.path.realpath(sys.argv[1]))" path/to/file

In each case, path/to/file can be either a relative or absolute path.


Use the readlink utility from the coreutils package.

MY_PATH=$(readlink -f "$0")