基本上我需要运行与shell脚本文件位置相关的路径脚本,我如何将当前目录更改为脚本文件所在的相同目录?
当前回答
基本版:
dir=$(dirname $0)
如果脚本可以通过$PATH调用,那么:
dir=$(dirname $(which $0))
如果脚本可能像这样调用:bash script.sh,那么:
dir=$(dirname $(which $0 2>/dev/null || realpath ./$0))
如果你感到极度不安全,那么:
dir="$(dirname -- "$(which -- "$0" 2>/dev/null || realpath -- "./$0")")"
其他回答
这应该能奏效:
echo `pwd`/`dirname $0`
它可能看起来很丑,这取决于它是如何被调用和cwd,但应该得到你需要去的地方(或者你可以调整字符串,如果你关心它的外观)。
So many answers, all plausible, each with pro's and con's & slightly differeing objectives (which should probably be stated for each). Here's another solution that meets a primary objective of both being clear and working across all systems, on all bash (no assumptions about bash versions, or readlink or pwd options), and reasonably does what you'd expect to happen (eg, resolving symlinks is an interesting problem, but isn't usually what you actually want), handle edge cases like spaces in paths, etc., ignores any errors and uses a sane default if there are any issues.
每个组件都存储在一个单独的变量中,您可以单独使用:
# script path, filename, directory
PROG_PATH=${BASH_SOURCE[0]} # this script's name
PROG_NAME=${PROG_PATH##*/} # basename of script (strip path)
PROG_DIR="$(cd "$(dirname "${PROG_PATH:-$PWD}")" 2>/dev/null 1>&2 && pwd)"
最初的帖子包含了解决方案(忽略回复,他们没有添加任何有用的东西)。有趣的工作是由前面提到的unix命令readlink和选项-f完成的。当以绝对路径和相对路径调用脚本时,此方法有效。
对于bash, sh, ksh:
#!/bin/bash
# Absolute path to this script, e.g. /home/user/bin/foo.sh
SCRIPT=$(readlink -f "$0")
# Absolute path this script is in, thus /home/user/bin
SCRIPTPATH=$(dirname "$SCRIPT")
echo $SCRIPTPATH
对于tcsh, csh:
#!/bin/tcsh
# Absolute path to this script, e.g. /home/user/bin/foo.csh
set SCRIPT=`readlink -f "$0"`
# Absolute path this script is in, thus /home/user/bin
set SCRIPTPATH=`dirname "$SCRIPT"`
echo $SCRIPTPATH
参见:https://stackoverflow.com/a/246128/59087
如果您正在使用bash....
#!/bin/bash
pushd $(dirname "${0}") > /dev/null
basedir=$(pwd -L)
# Use "pwd -P" for the path without links. man bash for more info.
popd > /dev/null
echo "${basedir}"
让我们把它变成一个POSIX在线程序:
a="/$0"; a="${a%/*}"; a="${a:-.}"; a="${a##/}/"; BINDIR=$(cd "$a"; pwd)
在包括BSD在内的许多兼容bourne的shell上进行了测试。
据我所知,我是作者,我把它放到了公共领域。更多信息见: https://www.bublina.eu.org/posts/2017-05-11-posix_shell_dirname_replacement/
推荐文章
- 如何合并2 JSON对象从2个文件使用jq?
- 在Bash中获取日期(比当前时间早一天)
- Linux: kill后台任务
- 在OSX中永久设置PATH环境变量
- 删除Bash脚本中的重复条目
- 如何将Bash命令的输出分配给变量?
- 如何在C程序中获取当前目录?
- PHP中的异步shell执行器
- Git显示“警告:永久添加到已知主机列表”
- 如何在Bash中逐行合并两个文件
- 检索Linux上单个进程的CPU使用情况和内存使用情况?
- 如何从远程SSH会话发送数据到本地剪贴板
- 我如何得到bash完成工作与别名?
- SSH端口转发~/。ssh /配置文件?
- 通过使用shell脚本替换文件名中的特定模式来重命名多个文件