防止 "dotting" a shell 执行它(在终止终端的函数中退出 vs 退出 shell )

prevent "dotting" a shell to execute it ( exit in a function killing the terminal vs exiting the shell )

如果启动带有 exit 语句的脚本,您必须将其作为子进程启动。

如果您在终端会话启动的当前 shell 内启动它(使用 . ./<scriptname> 任何退出都将关闭主 shell,它是在您的终端会话中启动的。

die () {
  echo "ERROR: $*. Aborting." >&2
  exit 1
}

[ -s "" ] || die "empty file"

echo "this should not be reached if  is not a nonempty file"

我知道这种情况。我想写一些东西来防止 Shell 这样 运行:

. shell.ksh params

如果有人用这种方式 运行 它应该会出错并显示一条消息。 我如何完成这项工作? 谢谢

根据 the excellent answer to a related question given by Dennis Williamson:

#!/bin/ksh

if [ "$_" != "[=10=]" ]; then
  echo "This script may not be sourced" >&2
  return
fi

: ...do other things here...