Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current directory of file after getting called by another bash script [duplicate]

So I have one bash script which calls another bash script. The second script is in a different folder.

script1.sh:
"some_other_folder/script2.sh"
# do something

script2.sh:
src=$(pwd) # THIS returns current directory of script1.sh...
# do something

In this second script it has the line src=$(pwd) and since I'm calling that script from another script in a different directory, the $(pwd) returns the current directory of the first script.

Is there any way to get the current directory of the second script using a simple command within that script without having to pass a parameter?

Thanks.

like image 518
Travv92 Avatar asked May 31 '13 04:05

Travv92


People also ask

How do I get the current 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 get the current directory name?

To determine the exact location of the current directory at a shell prompt and type the command pwd. This example shows that you are in the user sam's directory, which is in the /home/ directory. The command pwd stands for print working directory.

How can I get the source directory of a bash script from within the script itself?

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).

How do I get the current directory in Linux?

To print the current working directory, we use the pwd command in the Linux system. pwd (print working directory) – The pwd command is used to display the name of the current working directory in the Linux system using the terminal.


1 Answers

I believe you are looking for ${BASH_SOURCE[0]}, readlinkand dirname (though you can use bash string substitution to avoid dirname)

[jaypal:~/Temp] cat b.sh
#!/bin/bash

./tp/a.sh

[jaypal:~/Temp] pwd
/Volumes/Data/jaypalsingh/Temp

[jaypal:~/Temp] cat tp/a.sh
#!/bin/bash

src=$(pwd)
src2=$( dirname $( readlink -f ${BASH_SOURCE[0]} ) )
echo "$src"
echo "$src2"

[jaypal:~/Temp] ./b.sh
/Volumes/Data/jaypalsingh/Temp
/Volumes/Data/jaypalsingh/Temp/tp/
like image 113
jaypal singh Avatar answered Oct 22 '22 00:10

jaypal singh