Skip to content

Instantly share code, notes, and snippets.

@coltrane
Last active February 18, 2019 18:16
Show Gist options
  • Save coltrane/07bacde5686bdf823458dcaa9723e99b to your computer and use it in GitHub Desktop.
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)
#!/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\'
@coltrane
Copy link
Author

updated to support links to absolute paths, and also chains of multiple links.

@coltrane
Copy link
Author

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