请参阅shell脚本中的当前目录

One*_*ree 16 shell

如何引用shell脚本中的当前目录?

所以我有这个脚本调用同一目录中的另一个脚本:

#! /bin/sh

#Call the other script
./foo.sh 

# do something ...
Run Code Online (Sandbox Code Playgroud)

为此,我得到了 ./foo.sh: No such file or directory

所以我改成了:

#! /bin/sh

#Call the other script
foo.sh 

# do something ...
Run Code Online (Sandbox Code Playgroud)

但是这会调用foo默认情况下在PATH中的脚本.这不是我想要的.

所以问题是,./在shell脚本中引用的语法是什么?

hol*_*eek 20

如果两个脚本都在同一个目录中并且您收到./foo.sh: No such file or directory错误,那么最可能的原因是您从不同于他们所在目录的目录运行第一个脚本.将以下内容放在您的第一个脚本中以便调用到foo.sh作品无论在那里你调用从第一个脚本:

my_dir=`dirname $0`
#Call the other script
$my_dir/foo.sh
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“$0”在 _sourced_ 脚本中无法按预期工作。对于 bash,有 [`BASH_SOURCE`](https://mywiki.wooledge.org/BashFAQ/028) 替代 `$0`,它可以按预期工作。 (2认同)

Lui*_*23v 6

以下代码适用于空格,不需要bash即可工作:

#!/bin/sh

SCRIPTDIR="$(dirname "$0")"

#Call the other script
"$SCRIPTDIR/foo.sh"
Run Code Online (Sandbox Code Playgroud)

另外,如果要使用绝对路径,则可以执行以下操作:

SCRIPTDIR=`cd "$(dirname "$0")" && pwd`
Run Code Online (Sandbox Code Playgroud)