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

前端 未结 7 1787
臣服心动
臣服心动 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: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
    

提交回复
热议问题