Tags

, ,

For example, at the prompt: (for Linux)
./test/test2/test3/run.sh

say, content of run.sh:
. ${0%/*}/also_run.sh

then it would be expanded into,
. ./test/test2/test3/also_run.sh

notes: (for Windows)
– %~dp0 is the abs path of the current running (.bat) script
– “for /?” in cmd would list all the other %xxx0 variables

alternatives:
– dirname_regex=$(echo $0 | sed “s:/[^/.]*.sh$::;”) # regex
– dirname $0 # relative path
– dirname $(readlink /proc/$$/fd/255) # abs path
– regex to get everyting before the “last /” # relative path
– chdir to the folder, then pwd, then come back # abs path

motivatioin:
When situation 1 script would start another script and yet the “current” folder may not be the right folder to run all your scripts. So in this example, the script (and all the sub scripts) can carry the relative path info.
All scripts should be setup correctly (and no hard code path, etc).

reference:
http://www.gnu.org/s/bash/manual/bash.html#Shell-Parameter-Expansion
http://stackoverflow.com/questions/207959/equivalent-of-dp0-in-sh
http://stackoverflow.com/questions/5034076/what-does-dp0-mean-and-how-does-it-work

Advertisements