基本上我需要运行与shell脚本文件位置相关的路径脚本,我如何将当前目录更改为脚本文件所在的相同目录?
当前回答
对于tcsh,您可以使用:h变量修饰符来检索路径。
需要注意的是,如果脚本作为tcsh myscript执行。Csh,那么您将只获得脚本名称。一个解决方法是验证路径,如下所示。
#!/bin/tcsh
set SCRIPT_PATH = $0:h
if ( $SCRIPT_PATH == $0 ) then
set SCRIPT_PATH = "."
endif
$SCRIPT_PATH/compile.csh > $SCRIPT_PATH/results.txt
关于变量修饰语的更多信息可以在https://learnxinyminutes.com/docs/tcsh/上找到
其他回答
这应该能奏效:
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)"
cd $(dirname $(readlink -f $0))
灵感来自blueyed的回答
read < <(readlink -f $0 | xargs dirname)
cd $REPLY
基本版:
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")")"
推荐文章
- 如何在Makefile中设置子进程的环境变量
- 如何让“wc -l”打印没有文件名的行数?
- 有效地测试Linux上的端口是否打开?
- 如何从另一个文件A中删除文件B中出现的行?
- 对以制表符分隔的文件进行排序
- Shell脚本删除超过n天的目录
- 如何检查shell脚本中是否存在命令?
- 如何使用查找命令从列表中查找所有具有扩展名的文件?
- 如何打破一个循环在Bash?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 如何合并2 JSON对象从2个文件使用jq?
- 在Bash中获取日期(比当前时间早一天)
- Linux: kill后台任务
- 在OSX中永久设置PATH环境变量
- 删除Bash脚本中的重复条目