【问题标题】:prevent "dotting" a shell to execute it ( exit in a function killing the terminal vs exiting the shell ) [duplicate]防止“打点”一个shell来执行它(在函数中退出杀死终端与退出shell)[重复]
【发布时间】:2016-05-15 16:05:20
【问题描述】:

如果启动包含exit 语句的脚本,则必须将其作为子进程启动。

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

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

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

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

我知道这种情况。我想写一些东西来阻止外壳以这种方式运行:

. shell.ksh params

如果有人以这种方式运行它,它应该会出错并显示一条消息。 我该怎么做? 谢谢

【问题讨论】:

  • 使用return 而不是exit。回复here,我搜索了“bash exit from source file”,这是第一个结果
  • 返回程序将继续。它会从函数而不是程序中出来,我希望脚本退出:当它“死”时继续进行
  • @123, ...但退出脚本是die 意图的一部分;这里的问题是它是父shell,而不仅仅是脚本,正在退出。
  • 嗯。在 bash 中,您可以在顶层使用 return 在获取时退出但在运行时不退出,但这不适用于 ksh。
  • (旁白:是的,这是重复的,但我认为即使如此,它也会为网站增加价值;我可以合理地看到与此匹配的有用搜索词,但不是它重复的问题,即把骗子留在数据库中的重点)。

标签: bash shell unix sh ksh


【解决方案1】:

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

#!/bin/ksh

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

: ...do other things here...

【讨论】:

  • 对于这个美妙的解决方案,唯一需要记住的就是它应该在任何类型的 shell 语句之前。否则它会毁了演出
猜你喜欢
  • 1970-01-01
  • 2012-10-07
  • 2018-08-06
  • 2012-06-23
  • 2018-11-26
  • 2014-11-04
  • 2013-03-14
  • 1970-01-01
相关资源
最近更新 更多