简体   繁体   English

Shell 脚本当前目录?

[英]Shell script current directory?

What is current directory of shell script? shell 脚本的当前目录是什么? 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:下面是一个将打印 PWD 和安装目录的片段:

#!/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.通过在子 shell 中切换目录,我们可以调用pwd并获得脚本的正确路径,而不管上下文如何。

You can then use $DIR as "$DIR/path/to/file"然后,您可以将$DIR用作"$DIR/path/to/file"

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

You could do this yourself by checking the output from pwd when running it.您可以通过在运行时检查pwd的输出来自己执行此操作。 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你也可以完全使用 posix shell 脚本来完成它

#!/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:添加到mnabil的评论中,我认为最优化和逻辑的方式是:

realpath `dirname $0`

or with $(), if you don't mind.或者使用 $(),如果你不介意的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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