Always get the full path of a relative file in bash

I have a bash script located in /home/http/mywebsite/bin/download.sh

I have a config file in /home/http/mywebsite/config/config.yaml

Now I want to read the yaml file no matter where I execute my script.

The problem: When I cd into /home/http/mywebsite/bin/ and run ./download.sh everything works.

When I cd into /home/ and run http/mywebsite/bin/download.sh it can not find the config file because of the relative path.

How do I make sure I can always read the config file no matter where I execute the script. It is always located 4 directories up from the script in config/config.yaml

The script looks like this:

#!/bin/bash
# This will give me the root directory of my project which is /home/http/mywebsite/
fullpath="$( cd ../"$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cat ${fullpath}config/config.yaml

This works if I execute it inside the directory where the script is.

If I execute the script from another directory such as /home/ I get the following error:

cd: ../http/mywebsite/bin: No such file or directory
cat: config/config.yaml: No such file or directory

Solution?

If it is possible it would be great with a code snippet that can traverse up a path N amount of times, this would solve my problem. But it is too advanced for me.

For example you can set a variable "cd_up=1" how many times to go up. The run the loop/sed or whatever magic.

And it would turn the absolute string from: /home/http/mywebsite/bin/ into: /home/http/mywebsite/

And changing it to 2 it would change the string to: /home/http/


Managed to solve it finally by using:

#!/bin/bash
cd "$(dirname "$0")"
BASE_DIR=$PWD
# Root directory to the project
ROOT_DIR=${BASE_DIR}/../
cat ${ROOT_DIR}config/config.yaml

This allows me to execute the script no matter where I am.


You can use which command to determine absolute path of the executing script no matter where you are running

BASE_DIR=$(which $0 | xargs dirname)
ROOT_DIR=${BASE_DIR}/../..
cat ${ROOT_DIR}/config/config.yaml

Lets try printing the path from different locations.

-bash-4.1$ /tmp/dir.sh
$0 - /tmp/dir.sh. Absolute path - /tmp
-bash-4.1$ cd /tmp
-bash-4.1$ ./dir.sh
$0 - ./dir.sh. Absolute path - /tmp
-bash-4.1$
-bash-4.1$ cd /usr/bin
-bash-4.1$ ../../tmp/dir.sh
$0 - ../../tmp/dir.sh. Absolute path - /tmp
链接地址: http://www.djcxy.com/p/9740.html

上一篇: 获取导出函数的调用者脚本

下一篇: 总是在bash中获取相关文件的完整路径