Linux Shell脚本当前目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9889938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:26:09  来源:igfitidea点击:

Shell script current directory?

linuxdirectoryshworking-directory

提问by Suzan Cioc

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

shell脚本的当前目录是什么?我从哪个当前目录调用它?或者脚本所在的这个目录?

采纳答案by Merouane KHALILI

The current(initial) directory of shell script is the directory from which you have called the script.

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

回答by keyser

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

您可以通过检查pwd运行时的输出来自己完成此操作。这将打印您当前所在的目录。不是剧本。

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

如果您的脚本不切换目录,它将打印您从中运行它的目录。

回答by krg

As already mentioned, the location will be where the script was called from. If you wish to have the script reference it's install 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 
DIR="$( cd "$( dirname "
echo "the PWD is : ${pwd}"
" )" && pwd )"
) echo "Script location: ${BASEDIR}"

回答by saada

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

大多数答案都会为您提供当前路径并且是上下文相关的。为了从任何目录运行您的脚本,请使用以下代码段。

##代码##

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

通过在子 shell 中切换目录,我们可以调用pwd并获取脚本的正确路径,而无需考虑上下文。

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

然后你可以使用$DIR作为"$DIR/path/to/file"

回答by Sachin Java

To print the current working Directory i.e. pwd just type command like:

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

##代码##