bash - 确定执行 Bash 脚本的路径

标签 bash

<分区>

在Windows 命令脚本中,可以使用%~dp0 确定当前执行脚本的目录 路径。例如:

@echo Running from %~dp0

Bash 中的等价物是什么?脚本?

最佳答案

对于相对路径(即直接等效于 Windows 的 %~dp0):

MY_PATH="$(dirname -- "${BASH_SOURCE[0]}")"
echo "$MY_PATH"

对于绝对的规范化路径:

MY_PATH="$(dirname -- "${BASH_SOURCE[0]}")"            # relative
MY_PATH="$(cd -- "$MY_PATH" && pwd)"    # absolutized and normalized
if [[ -z "$MY_PATH" ]] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
fi
echo "$MY_PATH"

关于bash - 确定执行 Bash 脚本的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/630372/

相关文章:

linux - 如果没有停止,需要在 1 小时内重新启动服务器脚本

python - 在 Python 中定期获取 bash 命令的输出

Linux 命令输出未被重定向

linux - 如何编写 shell 脚本以从 sar 报告中查找 ram 利用率的最小最大值和平均值

regex -\0 在 sed 中是什么意思?

执行命令后 PHP 脚本挂起

python : ImportError: No module named numpy

带有停止/启动选项的 Linux bash 脚本

bash:通过 ssh 并行执行命令

linux - 将从一个命令获取的每个文件作为参数传递给另一个命令