Shell – How to source `. filename` reliably

posixshell

The current POSIX spec does not specify any options for dot . builtin.

If I do something like:

$ echo 'echo .' > /tmp/-foo
$ PATH=/tmp "$shell" -c '. -foo'

then the result is varied between shells:

  • dash, ash, ksh88, Bourne shell, schily sh, schily osh, heirloom sh work well.
  • bash, yash, ksh93, pdksh, mksh, posh don't. Changing the command to . -- -foo works in these shells.

And also, using -- is a non compliant way, because POSIX spec says that builtin which are not conformed to Utility Syntax Guidelines will ignore --.

zsh is the only shell that works with both cases.

So how can I make . filename work reliably in Bourne-like or POSIX compliant shells?

Best Answer

To avoid shell-dependent effects, pass a full path to .. . /absolute/path/to/script and . relative/path/to/script work in all shells.

PATH lookup is rarely useful for sourced scripts anyway. If you do want PATH lookup, then you can do the lookup manually in case the filename starts with -. Or you can require that the filename does not start with -, to keep things simple.

Related Question