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.
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.
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.
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).
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.
I believe you are looking for ${BASH_SOURCE[0]}
, readlink
and 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/
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