Issue
So I know the basics of relative paths in Linux...
but what if I want to run an executable (./exeToRun) relative to a parental folder? Do I use three dots?
Example
File stucture
project
│ README.md
│ file001.txt
│
└───folder1
│ │ exeToRun
│ │ file012.txt
│ │
│ └───subfolder1
│ │ myScript.py
│ │ file112.txt
│ │ ...
│
└───folder2
│ file021.txt
│ file022.txt
If I wanted to call ./exeToRun executable from myScript.py, relatively, I would assume the syntax would be .../folder1/exeToRun
. Two dots since it's relative to parent folder and one dot since its an executable.
Now I know this is incorrect, but I'm looking for some clarity on how to correctly achieve this functionality.
Solution
You'd use two dots (../exeToRun
); there's no additional "dot since its an executable", this is just a plain path.
In the usual case of ./exeToRun
, the single dot just means "in the current folder", not something about the file being executable. The reason it's needed is because if a command doesn't contain an explicit path (i.e. at least one "/"), the system will look for it in the various binaries directories in your $PATH
(i.e. /bin, /usr/bin, etc); putting ./
before the executable name overrides that by explicitly saying "in the current directory..."
HOWEVER, when you use .
and ..
like this, they're relative to the process's current working directory, which isn't necessarily the directory your script is in. If you cd
into the script's directory and run it with ./scriptname
, then yes it'll be the script's directory, but if you're somewhere else and run the script by its path... then the script's working directory will be wherever you happened to be when you ran the script.
If you want to run an executable relative to the script's directory, you need to first find the script's directory, and that's not always easy (or even possible). See "How can I get the source directory of a Bash script from within the script itself?" and BashFAQ #28: How do I determine the location of my script?
Answered By - Gordon Davisson Answer Checked By - Willingham (WPSolving Volunteer)