I need to get the path of the script. I can do that using pwd
if I am already in the same directory, I searched online and I found this
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
But i don't how to use that.
Join Stack Overflow to learn, share knowledge, and build your career.
Bash maintains a number of variables including BASH_SOURCE
which is an array of source file pathnames.
${}
acts as a kind of quoting for variables.
$()
acts as a kind of quoting for commands but they're run in their own context.
dirname
gives you the path portion of the provided argument.
cd
changes the current directory.
pwd
gives the current path.
&&
is a logical and
but is used in this instance for its side effect of running commands one after another.
In summary, that command gets the script's source file pathname, strips it to just the path portion, cd
s to that path, then uses pwd
to return the (effectively) full path of the script. This is assigned to DIR
. After all of that, the context is unwound so you end up back in the directory you started at but with an environment variable DIR
containing the script's path.
DIR="$( pwd )"
– Ouroborus
Sep 8 '16 at 22:40
${BASH_SOURCE[0]}
instead of ${BASH_SOURCE}
. Otherwise it is perfect.
– Bruno Bronosky
Feb 20 '18 at 21:28
dirname $0
(i.e. it ensures the path is absolute with only shell builtin commands, as discussed in stackoverflow.com/a/3915420/597742 and other answers to that question).
– ncoghlan
Mar 9 '18 at 3:44
echo "script=$0 dirForScript=$DIR"
? You should show what you have tried to solve your problem. If you put yourDIR=...
code and myecho script=...
in a script and call the main script from different directories you should see the same result. If not, then that is an interesting Q and you can update your Q with why it "isn't working" . Good luck. – shellter Sep 6 '16 at 3:28sh /full/path/to/filename.sh
. That should work. Then you have to add/full/path/to
to your PATH env variable. For something so simple, it can be very confusing at first. Don't give up, but find a good linux tutorial and read thru about how/why of PATH. Good luck. (Going to bed ;-) . – shellter Sep 6 '16 at 3:40