简体   繁体   中英

How to read the current folder from a script when it's called with source (same shell) or bash (subshell)?

This is a hard one, as I have researched for a few hours and could not find a solution that works, so I combined a few of solutions that I found and this is the results:

"$( cd "$( dirname "${BASH_SOURCE[0]}" )" && dirname -- "$(readlink -f -- "$0")" )"

If anyone has a simpler one, please share otherwise, enjoy!

I don't think that there is a solution for bash which works in every circumstance (for instance when sourcing a file via a link), but this approach might work most of the time:

${BASH_SOURCE[0]} contains the name of the script including PATH component, in the way it is invoked. If it was invoked via a $PATH search, it contains that respective PATH. Hence, dirname "${BASH_SOURCE[0]}" would be the directory, where the script is located (either as relative or absolute path). Consequently, readlink -f -- $(dirname "${BASH_SOURCE[0]}") would output the absolute path to this directory. Hence to locate other_script in the same directory would be:

source "$(readlink -f -- $(dirname "${BASH_SOURCE[0]}"))/other_script" # bash

You tagged your question also for zsh . In Zsh, things are a bit simpler. You find your script (plus directory part) in $0 . The absolute path of the directory is hence returned $0:A , giving you

source $0:A/other_script # zsh

Of course, if you need this information only for sourcing the other script, you don't need to get the absolute path to other_script . The relative path would do as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM