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?
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.
You can use the dot ( . ), the ~+ tilde expansion, the pwd command or the $PWD variable to represent the current working directory (CWD).
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With