回答

收藏

如何从脚本本身中获取 Bash 脚本的源目录?

技术问答 技术问答 361 人阅读 | 0 人回复 | 2023-09-11

如何获得目录路径?Bash脚本位于,里面那个脚本?
- m% W* [5 {0 s# |5 Z  O0 l. P我想使用 Bash 脚本是另一个应用程序的启动器。我想把工作目录改成 Bash 脚本所在的目录使我能够操作目录中的文件,如下所示:
3 C5 w( ]9 I% @% ^9 ]7 C
    $ ./application" s/ V, q4 M% P8 f& f; x
               3 z% h7 O9 l1 a7 h1 @
    解决方案:                                                               
+ X$ F0 F. Y. ]" L* ~5 l                                                               
    #!/usr/bin/env bashSCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ): x& Q6 A5 Q( p5 o2 D5 G+ L: z
这是一个有用的单行程序,无论从哪里调用脚本,它都会为您提供脚本的完整目录名称。
) l2 Y. E2 Z1 U3 o  ]( g只要用于查找脚本路径的最后一个组件不是符号链接(目录链接正常),它就会工作。如果您想分析脚本本身的任何链接,您需要更多的解决方案:
1 P" {: Q' A- ~9 S1 s) W3 Z
    #!/usr/bin/env bashSOURCE=${BASH_SOURCE[0]}while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink  DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )  SOURCE=$(readlink "$SOURCE")  [[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink,we need to resolve it relative to the path where the symlink file was locateddoneDIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
    0 S4 |1 y$ t! c" o
最后一个将适用于别名,source、bash -c、 任何组合,如符号链接。
' f# n$ h8 ^+ g( Y& f注意:如果您cd在运行此代码段之前,结果可能不正确!
- V& h# [" m: T* X. _: R另外,如果用户巧妙地覆盖 cd将输出重定向 stderr(包括转义序列,如 Mac 上调时请注意)$CDPATHgotchas和 stderr 输出副作用update_terminal_cwd >&2。>/dev/null 2>&1在cd在命令结束时添加这两种可能性。
: i" C3 @) @! v/ y1 R要了解它是如何工作的,请尝试操作更详细的表格:* L1 T' R$ |- F+ s7 w+ g3 u
    #!/usr/bin/env bashSOURCE=${BASH_SOURCE[0]}while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink  TARGET=$(readlink "$SOURCE")  if [[ $TARGET == /* ]]; then    echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"    SOURCE=$TARGET  else    DIR=$( dirname "$SOURCE" )  echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"    SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink,we need to resolve it relative to the path where the symlink file was located  fidoneecho "SOURCE is '$SOURCE'"RDIR=$( dirname "$SOURCE" )DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )if [ "$DIR" != "$RDIR" ]; then  echo "DIR '$RDIR' resolves to '$DIR'"fiecho "DIR is '$DIR'"2 v8 x7 R% W$ q
它将打印以下内容:
* j* K6 D' n# S4 Y- ]! R* I
    SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')SOURCE is './sym2/scriptdir.sh'DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'6 X! n" c, B4 O, b
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则