19

How do I refer to the current directory in a shell script?

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

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. This is not what I want.

So the question is, what's the syntax to refer ./ in a shell script?

1
  • 1
    ./ means the current working directory, not the directory that stores the currently executing script file. I'm not sure of any mechanism to get the directory containing the currently executing script. But if your first script is in the PATH, then so is the second script...
    – sarnold
    Commented Jun 5, 2012 at 22:39

6 Answers 6

26

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:

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

The following code works well with spaces and doesn't require bash to work:

#!/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`
1

This might help you: Unix shell script find out which directory the script file resides?

But as sarnold stated, "./" is for the current working directory.

1

In order to make it POSIX:

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

Tested on many Bourne-compatible shells including the BSD ones.

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

1

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

$script_dir/foo.sh

Reference: Alex Che's comment above.

0

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:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.