Skip to content

Instantly share code, notes, and snippets.

@573
Created February 11, 2020 08:41
Show Gist options
  • Save 573/26171868a25d4045773e38692cc3d0b5 to your computer and use it in GitHub Desktop.
Save 573/26171868a25d4045773e38692cc3d0b5 to your computer and use it in GitHub Desktop.
How to get the full path of a shell script to itself as data
#!/bin/bash
set -o nounset # Exit if undefined variable is used.
set -o errexit # Exit after first command failure.
set -o pipefail # Exit if any part of the pipe fails.
# set -o xtrace
echo "--- ${BASH_SOURCE[0]:-NOTSET}"
echo "See https://stackoverflow.com/q/242538/3320256 and https://stackoverflow.com/q/4774054/3320256"
echo -e " "
echo "--- direct variant:"
./nightly/inner.sh
echo -e " "
echo "--- source variant:"
. ./nightly/inner.sh
__dir="$(dirname "$(readlink -f "${BASH_SOURCE[0]:-NOTSET}")")"
BASEDIR="$("${__dir}/nightly/sets.sh")"
echo -e " "
echo "BASEDIR: $BASEDIR"
#!/bin/bash
# nightly/inner.sh
set -o nounset # Exit if undefined variable is used.
set -o errexit # Exit after first command failure.
set -o pipefail # Exit if any part of the pipe fails.
# set -o xtrace
set +o nounset
echo "called from "$(pwd)/$line
set -o nounset
echo "\$0 "$(readlink -f "$0")
echo "BASH_SOURCE "$(readlink -f "$BASH_SOURCE")
echo "BASH_SOURCE index 0 "$(readlink -f "${BASH_SOURCE[0]:-NOTSET}")
echo "BASH_SOURCE index 1 "$(readlink -f "${BASH_SOURCE[1]:-NOTSET}")
echo "~ index 0 folder "$(dirname "$(readlink -f "${BASH_SOURCE[0]:-NOTSET}")")
#!/bin/bash
# nightly/sets.sh
set -o nounset # Exit if undefined variable is used.
set -o errexit # Exit after first command failure.
set -o pipefail # Exit if any part of the pipe fails.
# set -o xtrace
cd "$(dirname "$(readlink -f "$0")")/../.." || exit; pwd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment