How to get the full path from the running bash script
If you need to get an absolute path of the script folder within the running shell script you may use readlink and dirname commands:
#!/bin/sh echo $(dirname $(readlink -f $0))
or (credits to kazoolist)
#!/bin/sh echo $(dirname $(readlink -f ${BASH_SOURCE[0]}))
which will work when script is run using “source”.
A note:
If it’s possible that the script desiring it’s own path is being run by being sourced (http://ss64.com/bash/period.html), rather than working off of $0 you’ll want to work from ${BASH_SOURCE[0]}, so the full command would be:
echo $(dirname $(readlink -f ${BASH_SOURCE[0]}))
Thanks for the more reliable solution!
If a set of files path is stored in another file. Now how to find the absolute path without using sed or substitution.
for eg:
Toshare.txt contains
~/Test/File1.txt
~/Best/song1.mp3
now reading this in a variable say ts and readlink -f $ts will fail.
otherwise how to check this condition
ts=”~/Test/File1.txt” —-> readlink fails (how to make it work)
ts=~/Test/File1.txt ——> readlink works
The shebang line is actually misleading:
#!/bin/sh
It should read:
#!/bin/bash
Since the solution involving readlink is only usable with /bin/bash but not with a plain /bin/sh. As it stands, a script containing the above lines will fail with:
./tst2.sh: 2: Bad substitution
dirname: missing operand
Try `dirname –help’ for more information.