7

I have one script with common functions that is included in other my scripts with:

. ~/bin/fns

Since my ~/bin path is on the PATH, is there a way to prevent users to execute fns from command line (by returning from the script with a message), but to allow other scripts to include this file?

(Bash >= 4)

3
  • Axel has given a good solution. But another question remains: if it is not supposed to be executable, why do you put it in the PATH in the first place? Commented Apr 9, 2014 at 12:39
  • Just for convenience. All executable scripts are in the same folder, so one/two non-executable files would not make a difference. Commented Apr 9, 2014 at 12:40
  • @AndreasBombe The source built-in also utilizes PATH. Commented Apr 9, 2014 at 12:41

4 Answers 4

11

Just remove the executable bit with chmod -x . ~/bin/fns. It will still work when sourced, but you can't call it (accidentally) by its name anymore.

Sign up to request clarification or add additional context in comments.

1 Comment

dumb me, sometimes i cant see the obvious :)
5

Add the following at the beginning of the script you want to be only allowed to be sourced:

if [ ${0##*/} == ${BASH_SOURCE[0]##*/} ]; then 
    echo "WARNING"
    echo "This script is not meant to be executed directly!"
    echo "Use this script only by sourcing it."
    echo
    exit 1
fi

This will check if the current script and executed shell script file basenames match. If they match, then obviously you are executing it directly so we print a message and exit with status 1.

Comments

4

Some scripts at my workplace use a special shebang

#!/bin/echo Run:.

which returns

Run:. <pathname>

when you use it as a command.

2 Comments

I would be curious to see how this special case would work if you have an example..
I just saw this after seven years, and I really like the idea. This is cool!
1
if ! (return 0 2>/dev/null) ; then
  echo "Error: direct invocation disallowed"
  exit 1
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.