How do I get the absolute directory of a file in bash?

前端 未结 7 1741
臣服心动
臣服心动 2020-12-04 14:03

I have written a bash script that takes an input file as an argument and reads it.
This file contains some paths (relative to its location) to additional files used.

相关标签:
7条回答
  • 2020-12-04 14:39

    Problem with the above answer comes with files input with "./" like "./my-file.txt"

    Workaround (of many):

        myfile="./somefile.txt"
        FOLDER="$(dirname $(readlink -f "${ARG}"))"
        echo ${FOLDER}
    
    0 讨论(0)
  • 2020-12-04 14:43

    I have been using readlink -f works on linux

    so

    FULL_PATH=$(readlink -f filename)
    DIR=$(dirname $FULL_PATH)
    
    PWD=$(pwd)
    
    cd $DIR
    
    #<do more work>
    
    cd $PWD
    
    0 讨论(0)
  • 2020-12-04 14:48
    $cat abs.sh
    #!/bin/bash
    echo "$(cd "$(dirname "$1")"; pwd -P)"
    

    Some explanations:

    1. This script get relative path as argument "$1"
    2. Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
    3. Then we cd "$(dirname "$1"); into this relative dir
    4. pwd -P and get absolute path. The -P option will avoid symlinks
    5. As final step we echo it

    Then run your script:

    abs.sh your_file.txt
    
    0 讨论(0)
  • 2020-12-04 14:50

    Take a look at the man page for realpath, I use that and something like:

    CONTAININGDIR=$(realpath ${FILEPATH%/*})

    to do what it sounds like you're trying to do.

    0 讨论(0)
  • 2020-12-04 14:58

    Try our new Bash library product realpath-lib over at GitHub that we have given to the community for free and unencumbered use. It's clean, simple and well documented so it's great to learn from. You can do:

    get_realpath <absolute|relative|symlink|local file path>
    

    This function is the core of the library:

    if [[ -f "$1" ]]
    then
        # file *must* exist
        if cd "$(echo "${1%/*}")" &>/dev/null
        then
            # file *may* not be local
            # exception is ./file.ext
            # try 'cd .; cd -;' *works!*
            local tmppwd="$PWD"
            cd - &>/dev/null
        else
            # file *must* be local
            local tmppwd="$PWD"
        fi
    else
        # file *cannot* exist
        return 1 # failure
    fi
    
    # reassemble realpath
    echo "$tmppwd"/"${1##*/}"
    return 0 # success
    
    }
    

    It's Bash 4+, does not require any dependencies and also provides get_dirname, get_filename, get_stemname and validate_path.

    0 讨论(0)
  • 2020-12-04 15:01

    This will work for both file and folder:

    absPath(){
        if [[ -d "$1" ]]; then
            cd "$1"
            echo "$(pwd -P)"
        else 
            cd "$(dirname "$1")"
            echo "$(pwd -P)/$(basename "$1")"
        fi
    }
    
    0 讨论(0)
提交回复
热议问题