Skip to content

Instantly share code, notes, and snippets.

@rikvermeer
Last active September 22, 2022 18:15
Show Gist options
  • Save rikvermeer/f8c80f7922840a2d405c9129a2456b23 to your computer and use it in GitHub Desktop.
Save rikvermeer/f8c80f7922840a2d405c9129a2456b23 to your computer and use it in GitHub Desktop.
bash file that can be sourced or executed. knows where to look for files
#!/usr/bin/env bash
CURDIR=${PWD}
COMMAND="${BASH_SOURCE:-$0}"
TARGET=$(basename $COMMAND)
TARGET_DIR="$( cd "$(dirname $COMMAND)" ; pwd -P )"
function main() {
echo "Hello ${@}"
echo "Curdir = ${CURDIR}"
echo "Command = ${COMMAND}"
echo "Target dir (pwd) = ${TARGET_DIR}"
echo "Target = ${TARGET}"
}
# Execute function if file is not being sourced
[[ $0 != "$BASH_SOURCE" ]] || main $@
@rikvermeer
Copy link
Author

Execute as bash script

$ ./workspace/project/tmp.sh f a
Hello f a
Curdir = /Users/home/you
Command = ./workspace/project/tmp.sh
Target dir (pwd) = /Users/home/you/workspace/project
Target = tmp.sh

Source script

$ source ./workspace/project/tmp.sh
$ main f a
Hello f a
Curdir = /Users/home/you
Command = ./workspace/project/tmp.sh
Target dir (pwd) = /Users/home/you/workspace/project
Target = tmp.sh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment