Last active
February 18, 2019 18:16
-
-
Save coltrane/07bacde5686bdf823458dcaa9723e99b to your computer and use it in GitHub Desktop.
How can a bash (or sh) script reliably get a path to itself? (one-liner)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# reliable path to current script in one-liner (handles spaces) | |
scriptpath=$(l=$(which "$0"); while :; do cd "$(dirname "$l")"; p=$(basename "$l"); \ | |
l=$(readlink "$p") || break; done; echo $(pwd)/$p) | |
echo \'$scriptpath\' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# this function resolves links recursively, leaving you with | |
# a direct path to a real file. Handles spaces in paths correctly. | |
# if the file doesn't actually exist, strange things will happen. | |
function reslinks { | |
(link=$1; | |
while : ; do cd "$(dirname "$link")"; path=$(basename "$link"); link=$(readlink "$path") || break; done | |
echo $(pwd)/$path) | |
} | |
# use the reslinks function get a reliable path to this script | |
# (the `which $0` is only needed on platforms where $0 doesn't | |
# include the full path to scripts that were invoked via $PATH) | |
# | |
scriptpath=$(reslinks "$(which "$0")") | |
echo \'$scriptpath\' |
Improved (and shortened) the code a little. Added the example with a general purpose reslinks function. Added support for paths that include spaces.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
updated to support links to absolute paths, and also chains of multiple links.