简体   繁体   中英

Getting name of containing Folder

I have a shell script that I want to copy in many directories

Inside this script, How can I initialize the variable

PARENT_FOLDER

in a way to store in it the name (and not the absolute path) of the folder containing this script?

Note that this script may be run from any folder.

Thanks in advance.

Under most circumstances, the following gets the absolute path to the directory that the script is in:

PARENT_FOLDER=$(dirname "$(readlink -f "$0")")

(OSX and BSD might lack the -f option without which the path may still contain symbolic links.)

If you just want the name of the final directory in the path, just add one step:

PARENT_FOLDER=$(dirname "$(readlink -f "$0")")
PARENT_FOLDER=${PARENT_FOLDER##*/}

On systems lacking readlink -f but for which bash is available:

PARENT_FOLDER="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PARENT_FOLDER=${PARENT_FOLDER##*/}

And if lacking both readlink -f and bash:

PARENT_FOLDER="$( cd "$( dirname "$0" )" && pwd )"
PARENT_FOLDER=${PARENT_FOLDER##*/}

To get parent folder of Current Directory you can use following command

PARENT_FOLDER=$(pwd | awk -F"/" 'OFS="/"{$NF=""}1')

To Update

also below command can work

from man page of command dirname Print NAME with its trailing /component removed; if NAME contains no /'s, output '.' (meaning the current directory).

PARENT_FOLDER=$(dirname "$PWD") or

PARENT_FOLDER=$(dirname "$0")
PARENT_FOLDER=$(pwd | awk -F / '{if ($NF!="") print $NF; else print "/"}')

The best solution that worked for me on both mac and linux is

PARENT_FOLDER="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PARENT_FOLDER=${PARENT_FOLDER##*/}

It is a combination of the answer given in this link:

Getting the source directory of a Bash script from within

And the answer given by @John1024

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