How do you normalize a file path in Bash?

I want to transform /foo/bar/.. to /foo

Is there a bash command which does this?


Edit: in my practical case, the directory does exist.


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

Edit

Realpath appears not to be standard issue.

The closest you can get with the stock standard is

readlink -f  /path/here/.. 

Realpath appears to come from debian, and is not part of coreutils: http://packages.debian.org/unstable/utils/realpath Which was originally part of the DWWW package.

( also available on gentoo as app-admin/realpath )

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

Works the same as

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

in that it doesn't need the path to actually exist to normalise it.


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("%sn", realpath(argv[1], sPath));
    return 0;
}    

void usage(void)
{
    fprintf(stderr, "usage: %s PATHn", s_pMyName);
    exit(1);
}
链接地址: http://www.djcxy.com/p/56734.html

上一篇: “猫”EOF“如何在bash中工作?

下一篇: 你如何规范Bash中的文件路径?