【发布时间】:2018-02-07 19:50:45
【问题描述】:
这是基于another question of mine。我试图阻止使用脚本执行某些命令。我让脚本在交互式 shell 中完美运行,但对于非交互式 shell,它不会阻止它的执行。
/home/user/stop.sh(来源于.bashrc)
#!/usr/bin/env bash
shopt -s extdebug; stop_cmd () {
[ -n "$COMP_LINE" ] && return # not needed for completion
[ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # not needed for prompt
local this_command=$BASH_COMMAND;
echo $this_command" Not Allowed";
return 1
};
trap 'stop_cmd' DEBUG
/home/user/temp.sh
#!/usr/bin/env bash
ls
我使用@Inian 建议的 BASH_ENV 变量将我的脚本放入使用非交互式 shell 的脚本文件中。
在新的外壳中
#:export BASH_ENV=/home/user/stop.sh
#:ls
ls Not Allowed --> This is because of the source in .bashrc
#: --> Prompt appears. ls did not run
#:./temp.sh
./temp.sh: /usr/share/bashdb/bashdb-main.inc: No such file or directory
./temp.sh: warning: cannot start debugger; debugging mode disabled
ls Not Allowed --> Because of the $BASH_ENV
Directory contents displayed --> ls ended up running
#: --> Prompt appears after executing temp.sh
但是如果我直接在temp.sh 中source stop.sh 不会显示这种行为,它就像一个魅力。
【问题讨论】:
-
我没有这样做!但是你能解释一下你是如何在上面的代码中使用
BASH_ENV的吗?以及传递给它的文件内容 -
@Inian 对不起,如果不是很明显......让我编辑这个问题。我知道你没有这样做????
-
抱怨反对票是吸引更多人的好方法。这不是它应有的工作方式,但考虑到您正在寻求帮助并且显然仍在学习该网站的规则的情况,这并不引人注目。
-
顺便说一句,
echo $this_command" Not Allowed";看起来很奇怪。没有特别的理由将静态字符串放在双引号内,但有很多理由将$this_command放在引号内。另见stackoverflow.com/questions/10067266/… -
我没有尝试复制,但看起来
trap 'stop_cmd' DEBUG没有被继承。我推测env是这里的罪魁祸首。