bash 如何将当前工作目录设置为脚本目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3349105/
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-09-09 19:31:43  来源:igfitidea点击:

How to set current working directory to the directory of the script?

bashpathscripting

提问by jameshfisher

I'm writing a bash script. I need the current working directory to always be the directory that the script is located in.

我正在编写一个 bash 脚本。我需要当前工作目录始终是脚本所在的目录。

The default behavior is that the current working directory in the script is that of the shell from which I run it, but I do not want this behavior.

默认行为是脚本中的当前工作目录是我运行它的 shell 的目录,但我不想要这种行为。

回答by ndim

#!/bin/bash
cd "$(dirname "
cd "${0%/*}"
")"

回答by Paul Schulz

The following also works:

以下也有效:

dir=$(cd -P -- "$(dirname -- "
dir=$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
")" && pwd -P)

The syntax is thoroughly described in thisStackOverflow answer.

StackOverflow 答案中详细描述了语法。

回答by kenorb

Try the following simple one-liners:

尝试以下简单的单线:



For all UNIX/OSX/Linux

适用于所有 UNIX/OSX/Linux

cd "$(dirname "$(realpath "
cd "$(dirname "$(readlink -f "
cd "$(dirname "$(readlink -f "
cd "$(dirname "$(greadlink -f "
cd "${0%/*}"
")")"
")")"
" || realpath "
realpath () {
  [[  = /* ]] && echo "" || echo "$PWD/${1#./}"
}
")")"
")")";

Bash

重击

function realpath()
{
    f=$@
    if [ -d "$f" ]; then
        base=""
        dir="$f"
    else
        base="/$(basename "$f")"
        dir=$(dirname "$f")
    fi
    dir=$(cd "$dir" && /bin/pwd)
    echo "$dir$base"
}

Note: A double dash (--) is used in commands to signify the end of command options, so files containing dashes or other special characters won't break the command.

注意:命令中使用双破折号 (--) 表示命令选项的结束,因此包含破折号或其他特殊字符的文件不会破坏命令。

Note: In Bash, use ${BASH_SOURCE[0]}in favor of $0, otherwise the path can break when sourcing it (source/.).

注:在bash,使用${BASH_SOURCE[0]}赞成$0,否则路径可以采购时,它打破(source/ .)。



For Linux, Mac and other *BSD:

对于 Linux、Mac 和其他 *BSD:

cd "$(dirname "${BASH_SOURCE[0]}")"

Note: realpathshould be installed in the most popular Linux distribution by default (like Ubuntu), but in some it can be missing, so you have to install it.

注意:realpath默认情况下应该安装在最流行的 Linux 发行版中(如 Ubuntu),但在某些情况下可能会丢失,因此您必须安装它。

Note: If you're using Bash, use ${BASH_SOURCE[0]}in favor of $0, otherwise the path can break when sourcing it (source/.).

注意:如果您使用 Bash,请使用${BASH_SOURCE[0]}支持$0,否则在获取路径时可能会中断 ( source/ .)。

Otherwise you could try something like that (it will use the first existing tool):

否则,您可以尝试类似的操作(它将使用第一个现有工具):

#!/bin/bash
cd "$(dirname "
ln -sv ~/project/script.sh ~/bin/; 
~/bin/script.sh
")"


For Linux specific:

对于 Linux 特定:

#!/bin/bash
cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"


Using GNU readlink on *BSD/Mac:

在 *BSD/Mac 上使用 GNU readlink:

#!/bin/bash
mypath=`realpath 
if [ -L 
cd "`dirname $(readlink -f 
echo $PWD
)`"
] ; then ME=$(readlink
$ vim test

#!/bin/bash
pwd
:wq to save the test file.
) else ME=
chmod u+x test
fi DIR=$(dirname $ME)
` cd `dirname $mypath` pwd

Note: You need to have coreutilsinstalled (e.g. 1. Install Homebrew, 2. brew install coreutils).

注意:您需要coreutils安装(例如 1. Install Homebrew, 2. brew install coreutils)。



In bash

在 bash 中

In bash you can use Parameter Expansionsto achieve that, like:

在 bash 中,您可以使用参数扩展来实现,例如:

##代码##

but it doesn't work if the script is run from the same directory.

但如果脚本从同一目录运行,则它不起作用。

Alternatively you can define the following function in bash:

或者,您可以在 bash 中定义以下函数:

##代码##

This function takes 1 argument. If argument has already absolute path, print it as it is, otherwise print $PWDvariable + filename argument (without ./prefix).

此函数需要 1 个参数。如果参数已经有绝对路径,则按原样打印,否则打印$PWD变量 + 文件名参数(不带./前缀)。

or here is the version taken from Debian .bashrcfile:

或者这里是从 Debian.bashrc文件中获取的版本:

##代码##

Related:

有关的:

See also:

也可以看看:

How can I get the behavior of GNU's readlink -f on a Mac?

如何在 Mac 上获得 GNU 的 readlink -f 的行为?

回答by Dan Moulding

##代码##

It's easy. It works.

这很简单。有用。

回答by James McGuigan

The accepted answer works well for scripts that have not been symlinked elsewhere, such as into $PATH.

接受的答案适用于尚未在其他地方进行符号链接的脚本,例如 into $PATH.

##代码##

However if the script is run via a symlink,

但是,如果脚本通过符号链接运行,

##代码##

This will cd into the ~/bin/directory and not the ~/project/directory, which will probably break your script if the purpose of the cdis to include dependencies relative to ~/project/

这将 cd 进入~/bin/目录而不是~/project/目录,如果目的cd是包含相对于~/project/

The symlink safe answer is below:

符号链接安全答案如下:

##代码##

readlink -fis required to resolve the absolute path of the potentially symlinked file.

readlink -f需要解析潜在符号链接文件的绝对路径。

The quotes are required to support filepaths that could potentially contain whitespace (bad practice, but its not safe to assume this won't be the case)

需要引号来支持可能包含空格的文件路径(不好的做法,但假设情况并非如此是不安全的)

回答by Amardeep AC9MF

This script seems to work for me:

这个脚本似乎对我有用:

##代码##

The pwd command line echoes the location of the script as the current working directory no matter where I run it from.

无论我从哪里运行脚本,pwd 命令行都会将脚本的位置作为当前工作目录进行回显。

回答by rodnower

Get the real path to your script

获取脚本的真实路径

##代码##

(This is answer to the same my question here: Get the name of the directory where a script is executed)

(这是对我的相同问题的回答:获取执行脚本的目录的名称

回答by rodnower

##代码##

回答by Maverick Holdem

##代码##

PWD is an environment variable.

PWD 是一个环境变量。

回答by Chandan

If you just need to print present working directory then you can follow this.

如果您只需要打印当前工作目录,那么您可以按照此操作。

##代码##

Give execute permission:

赋予执行权限:

##代码##

Then execute the script by ./testthen you can see the present working directory.

然后执行脚本./test就可以看到当前的工作目录了。