Domanda

Non sono sicuro se questi percorsi sono duplicati. Dato il percorso relativo, come determino percorso assoluto utilizzando uno script di shell?

Esempio:

relative path: /x/y/../../a/b/z/../c/d

absolute path: /a/b/c/d
È stato utile?

Soluzione

questa fonte arriva:

#!/bin/bash

# Assume parameter passed in is a relative path to a directory.
# For brevity, we won't do argument type or length checking.

ABS_PATH=`cd "$1"; pwd` # double quotes for paths that contain spaces etc...
echo "Absolute path: $ABS_PATH"

È anche possibile fare una Perl one-liner, per esempio utilizzando Cwd::abs_path

Altri suggerimenti

Il metodo più affidabile che ho incontrato in UNIX è readlink -f:

$ readlink -f /x/y/../../a/b/z/../c/d
/a/b/c/d

Un paio di avvertenze:

  1. Questo ha anche l'effetto collaterale di risolvere tutti i collegamenti simbolici. Questo può o non può essere desiderabile, ma di solito è.
  2. readlink darà un risultato vuoto se si fa riferimento a una directory inesistente. Se si desidera supportare i percorsi inesistenti, utilizzo readlink -m invece. Purtroppo questa opzione non esiste in versioni di readlink rilasciati prima ~ 2005.

Uso

# Directory
relative_dir="folder/subfolder/"
absolute_dir="$( cd "$relative_dir" && pwd )"

# File
relative_file="folder/subfolder/file"
absolute_file="$( cd "${relative_file%/*}" && pwd )"/"${relative_file##*/}"
  • ${relative_file%/*} è stesso risultato di dirname "$relative_file"
  • ${relative_file##*/} è stesso risultato di basename "$relative_file"

Avvertimenti :. Non risolve i collegamenti simbolici (vale a dire non percorso non canonicalize) => maggio non distingue tutti i duplicati se si utilizzano i collegamenti simbolici


Uso realpath

realpath fa il lavoro. Un'alternativa è quella di utilizzare readlink -e (o readlink -f). Tuttavia realpath spesso non è installato di default. Se non si può essere sicuri realpath o readlink è presente, è possibile sostituire utilizzando Perl (vedi sotto).


Uso

Steven Kramer propone un alias di shell se realpath non è disponibile nel sistema:

$ alias realpath="perl -MCwd -e 'print Cwd::realpath(\$ARGV[0]),qq<\n>'"
$ realpath path/folder/file
/home/user/absolute/path/folder/file

o se si preferisce usare direttamente perl:

$ perl -MCwd -e 'print Cwd::realpath($ARGV[0]),qq<\n>' path/folder/file
/home/user/absolute/path/folder/file

Questo comando perl una riga usa Cwd::realpath. Ci sono infatti tre funzioni perl. Prendono un singolo argomento e restituiscono il percorso assoluto. Qui di seguito i dettagli sono da documentazione Perl5> Nucleo moduli> Cwd .

  • abs_path() utilizza lo stesso algoritmo getcwd(). I link simbolici e componenti relative-path (. e ..) hanno deciso di restituire il percorso canonico, proprio come realpath .

    use Cwd 'abs_path';
    my $abs_path = abs_path($file);
    
  • realpath() è un sinonimo di abs_path()

    use Cwd 'realpath';
    my $abs_path = realpath($file);
    
  • fast_abs_path() è una versione più pericolosa, ma potenzialmente più veloce di abs_path()

    use Cwd 'fast_abs_path';
    my $abs_path = fast_abs_path($file);
    

Queste funzioni sono esportati solo su richiesta => quindi utilizzare Cwd per evitare il "subroutine non definita" errore su punte da arielf . Se si desidera importare tutte queste tre funzioni, è possibile utilizzare una singola linea use Cwd:

use Cwd qw(abs_path realpath fast_abs_path);

Date un'occhiata a 'realpath'.

$ realpath

usage: realpath [-q] path [...]

$ realpath ../../../../../

/data/home

Dal momento che ho incontrato molte volte nel corso degli anni, e questa volta avevo bisogno di una versione portatile bash pura che potrei usare su OSX e Linux, sono andato avanti e ho scritto una:

La versione vivente vive qui:

https://github.com/keen99/shell-functions/tree/ master / resolve_path

ma per il bene di SO, ecco la versione attuale (Sento che è bene tested..but Sono aperto a feedback!)

Non potrebbe essere difficile farlo funzionare per Bourne shell pianura (sh), ma non ho provato ... ho come $ FUNCNAME troppo. :)

#!/bin/bash

resolve_path() {
    #I'm bash only, please!
    # usage:  resolve_path <a file or directory> 
    # follows symlinks and relative paths, returns a full real path
    #
    local owd="$PWD"
    #echo "$FUNCNAME for $1" >&2
    local opath="$1"
    local npath=""
    local obase=$(basename "$opath")
    local odir=$(dirname "$opath")
    if [[ -L "$opath" ]]
    then
    #it's a link.
    #file or directory, we want to cd into it's dir
        cd $odir
    #then extract where the link points.
        npath=$(readlink "$obase")
        #have to -L BEFORE we -f, because -f includes -L :(
        if [[ -L $npath ]]
         then
        #the link points to another symlink, so go follow that.
            resolve_path "$npath"
            #and finish out early, we're done.
            return $?
            #done
        elif [[ -f $npath ]]
        #the link points to a file.
         then
            #get the dir for the new file
            nbase=$(basename $npath)
            npath=$(dirname $npath)
            cd "$npath"
            ndir=$(pwd -P)
            retval=0
            #done
        elif [[ -d $npath ]]
         then
        #the link points to a directory.
            cd "$npath"
            ndir=$(pwd -P)
            retval=0
            #done
        else
            echo "$FUNCNAME: ERROR: unknown condition inside link!!" >&2
            echo "opath [[ $opath ]]" >&2
            echo "npath [[ $npath ]]" >&2
            return 1
        fi
    else
        if ! [[ -e "$opath" ]]
         then
            echo "$FUNCNAME: $opath: No such file or directory" >&2
            return 1
            #and break early
        elif [[ -d "$opath" ]]
         then 
            cd "$opath"
            ndir=$(pwd -P)
            retval=0
            #done
        elif [[ -f "$opath" ]]
         then
            cd $odir
            ndir=$(pwd -P)
            nbase=$(basename "$opath")
            retval=0
            #done
        else
            echo "$FUNCNAME: ERROR: unknown condition outside link!!" >&2
            echo "opath [[ $opath ]]" >&2
            return 1
        fi
    fi
    #now assemble our output
    echo -n "$ndir"
    if [[ "x${nbase:=}" != "x" ]]
     then
        echo "/$nbase"
    else 
        echo
    fi
    #now return to where we were
    cd "$owd"
    return $retval
}

Ecco un esempio classico, grazie a brew:

%% ls -l `which mvn`
lrwxr-xr-x  1 draistrick  502  29 Dec 17 10:50 /usr/local/bin/mvn@ -> ../Cellar/maven/3.2.3/bin/mvn

utilizzare questa funzione e restituirà il percorso -real-:

%% cat test.sh
#!/bin/bash
. resolve_path.inc
echo
echo "relative symlinked path:"
which mvn
echo
echo "and the real path:"
resolve_path `which mvn`


%% test.sh

relative symlinked path:
/usr/local/bin/mvn

and the real path:
/usr/local/Cellar/maven/3.2.3/libexec/bin/mvn

Può essere questo aiuta:

$path = "~user/dir/../file" 
$resolvedPath = glob($path); #   (To resolve paths with '~')
# Since glob does not resolve relative path, we use abs_path 
$absPath      = abs_path($path);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top