简体   繁体   中英

Shell script current directory?

What is current directory of shell script? I this current directory from which I called it? Or this directory where script located?

As already mentioned, the location will be where the script was called from. If you wish to have the script reference it's installed location, it's quite simple. Below is a snippet that will print the PWD and the installed directory:

#!/bin/bash
echo "Script executed from: ${PWD}"

BASEDIR=$(dirname $0)
echo "Script location: ${BASEDIR}"

Most answers get you the current path and are context sensitive. In order to run your script from any directory, use the below snippet.

DIR="$( cd "$( dirname "$0" )" && pwd )"

By switching directories in a subshell, we can then call pwd and get the correct path of the script regardless of context.

You can then use $DIR as "$DIR/path/to/file"

shell 脚本的当前(初始)目录是您从中调用脚本的目录。

You could do this yourself by checking the output from pwd when running it. This will print the directory you are currently in . Not the script.

If your script does not switch directories, it'll print the directory you ran it from .

要打印当前的工作目录,即 pwd,只需键入如下命令:

echo "the PWD is : ${pwd}"

you could also do it completely using posix shell script

#!/bin/sh

get_current_directory() {
    current_file="${PWD}/${0}"
    echo "${current_file%/*}"
}

CWD=$(get_current_directory)
echo "$CWD"

Adding to mnabil 's comment I think most optimized and logic way is:

realpath `dirname $0`

or with $(), if you don't mind.

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