简体   繁体   English

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

[英]Refer to the current directory in a shell script

How do I refer to the current directory in a shell script? 如何引用shell脚本中的当前目录?

So I have this script which calls another script in the same directory: 所以我有这个脚本调用同一目录中的另一个脚本:

#! /bin/sh

#Call the other script
./foo.sh 

# do something ...

For this I got ./foo.sh: No such file or directory 为此,我得到./foo.sh: No such file or directory

So I changed it to: 所以我改成了:

#! /bin/sh

#Call the other script
foo.sh 

# do something ...

But this would call the foo script which is, by default, in the PATH. 但是这会调用foo脚本,默认情况下是在PATH中。 This is not what I want. 这不是我想要的。

So the question is, what's the syntax to refer ./ in a shell script? 所以问题是,在shell脚本中引用./的语法是什么?

If both the scripts are in the same directory and you got the ./foo.sh: No such file or directory error then the most likely cause is that you ran the first script from a different directory than the one where they are located in. Put the following in your first script so that the call to foo.sh works irrespective of where you call the first script from: 如果两个脚本都在同一个目录中并且你得到了./foo.sh: No such file or directory错误,那么最可能的原因是你从不同的目录运行第一个脚本而不是它们所在的目录。将以下内容放在您的第一个脚本中,以便无论您从哪里调用第一个脚本,对foo.sh的调用foo.sh起作用:

my_dir=`dirname $0`
#Call the other script
$my_dir/foo.sh

The following code works well with spaces and doesn't require bash to work: 以下代码适用于空格,不需要bash工作:

#!/bin/sh

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

#Call the other script
"$SCRIPTDIR/foo.sh"

Also if you want to use the absolute path, you could do this: 此外,如果您想使用绝对路径,您可以这样做:

SCRIPTDIR=`cd "$(dirname "$0")" && pwd`

This might help you: Unix shell script find out which directory the script file resides? 这可能对您有所帮助: Unix shell脚本找出脚本文件所在的目录?

But as sarnold stated, "./" is for the current working directory . 但正如sarnold所说,“。/”代表当前的工作目录

script_dir="${BASH_SOURCE%/*}" # rm the last / and the file name from BASH_SOURCE

$script_dir/foo.sh

参考:Alex Che的评论如上。

The accepted solution does not work if you have a space in the path to the directory containing the scripts. 如果在包含脚本的目录的路径中有空格,则接受的解决方案不起作用。

If you can use bash, this worked for me: 如果你可以使用bash,这对我有用:

#!/bin/bash
SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
"${SCRIPTDIR}/foo.sh"

In order to make it POSIX: 为了使它成为POSIX:

a="/$0"; a=${a%/*}; a=${a:-.}; a=${a#/}/; BASEDIR=$(cd $a; pwd)

Tested on many Bourne-compatible shells including the BSD ones. 测试了许多与Bourne兼容的shell,包括BSD。

As far as I know I am the author and I put it into public domain. 据我所知,我是作者,我将其置于公共领域。 For more info see: https://blog.jasan.tk/posix/2017/05/11/posix_shell_dirname_replacement 有关详细信息,请参阅: https//blog.jasan.tk/posix/2017/05/11/posix_shell_dirname_replacement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM