2

What's a good POSIX compliant way to make a script both executable (a function from the script gets executed) and in-sourcable with the . command (nothing happens except (at least) 1 function becomes available?

I've tried:

src.sh:

#!/bin/sh -eu
FILENAME=src.sh
f() { echo hello from f; }
case $0 in ($FILENAME|*/$FILENAME) f "$@";; esac

and then tested it with:

( PATH=$PWD:$PATH; src.sh; . src.sh ; echo ===; f )

This appears to work as expected on Cygwin, MacOS and Linux.

Any suggestions on how to improve it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.