防止“点”一个外壳来执行它(退出功能,查杀终端和退出外壳)

问题描述:

如果启动一个脚本,其中包含exit语句,您必须将其作为子进程启动。防止“点”一个外壳来执行它(退出功能,查杀终端和退出外壳)

如果您启动它与你的终端会话启动电流壳内(使用. ./<scriptname>任何退出将关闭主外壳,一个沿着你的终端会话启动。

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 

如果有人要运行它这种方式,应以信息报错了 如何完成这件事 谢谢

+1

使用'return',而不是'exit'。回答[这里](http://stackoverflow.com/questions/3666846/how-do-you-return-to-a-sourced-bash-script),我搜索“bash退出源文件”,它是第一个结果 – 123

+0

程序将继续返回。它会从功能而不是程序中退出,我希望脚本退出:当它“死亡”时再继续进行 – user1874594

+0

@ 123,...但退出脚本是'die'的意图的一部分;这里的问题是它是父shell,而不仅仅是脚本,退出。 –

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... 
+0

唯一需要牢记的就是它应该在任何一种shell语句之前。否则它会毁掉这个节目 – user1874594