Because the OP didn't provide a sample script, I'm going to make one. It will do one thing. Run ls
in the directory of the script.
Yes, I know you can just do ls
without the ./
. But for this example, I'm pretending it is required, to demonstrate a script that uses the current directory of the script.
#!/usr/bin/env bash
ls ./
Save that script somewhere. I'll save it as /home/ubuntu/test/myscript
. Make it executable with chmod +x /home/ubuntu/test/myscript
. Now cd
to the directory where the script is (e.g., cd /home/ubuntu/test
), and run the script with ./myscript
:
ubuntu@computer:~/test$ ./myscript
myscript someRandomFile
So far, so good. But now lets run it from a different directory. For this example, I'm going to run it from the root directory (/
).
ubuntu@computer:~/test$ cd /
ubuntu@computer:/$ /home/ubuntu/test/myscript
bin dev home lib lib64 lost+found mnt proc run snap sys usr
boot etc init lib32 libx32 media opt root sbin srv tmp var
Oops. We wanted it to print the files in the location of the script, not the location of the user. Before we figure out the solution, think about why it does this for a moment. The answer is simple. ./
is relative to the user's current directory, not the one of the script.
To get the directory of the script from inside of the script, we will look at this Stack Overflow question.
The gist of it is simple: script_dir="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
will get the current directory of the script, and store it in the variable script_dir
.
Let's update the script accordingly. Our script is now this:
#!/usr/bin/env bash
script_dir="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
ls "$script_dir"
Let's run it, and see if it works:
ubuntu@computer:/$ /home/ubuntu/test/myscript
myscript someRandomFile
It works! It prints the files in the directory of the script, even when you are not in the same directory as the script, We're done. The overall idea is simple. In the script, ./
refers to the user's directory. "$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
refers to the directory the script is in. Update your script accordingly, and it should work.