Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to the current directory in a shell script

Tags:

shell

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?

like image 285
One Two Three Avatar asked Jun 05 '12 22:06

One Two Three


People also ask

How do I get the current directory shell?

To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd. This tells you that you are in the user sam's directory, which is in the /home directory. The command pwd stands for print working directory.

How do I refer to current directory?

You can use the dot ( . ), the ~+ tilde expansion, the pwd command or the $PWD variable to represent the current working directory (CWD).

How do I get current working directory in bash?

Print Current Working Directory ( pwd ) To print the name of the current working directory, use the command pwd . As this is the first command that you have executed in Bash in this session, the result of the pwd is the full path to your home directory.

How do I find the directory of a script?

pwd can be used to find the current working directory, and dirname to find the directory of a particular file (command that was run, is $0 , so dirname $0 should give you the directory of the current script).


1 Answers

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
like image 197
holygeek Avatar answered Oct 30 '22 07:10

holygeek