繁体   English   中英

如何从bash脚本中“隐藏”可执行文件?

[英]How to “hide” an executable from a bash script?

我想测试bash脚本的输出,当它依赖的其中一个可执行文件丢失时,所以我想运行该脚本的依赖项“隐藏”而不是其他。 PATH= ./script不是一个选项,因为脚本在到达我想要测试的语句之前需要运行其他可执行文件。 有没有一种方法可以在不改变文件系统的情况下从脚本中“隐藏”可执行文件?

举一个具体的例子,我想运行这个脚本但是从它隐藏git可执行文件(这是它的主要依赖项),以便我可以在这些条件下测试它的输出。

你可以使用builtin命令, hash

hash [-r] [-p filename] [-dt] [name]

每次调用哈希时,它都会记住指定为名称参数的命令的完整路径名,因此无需在后续调用中搜索它们。 ... -p选项禁止路径搜索,filename用作名称的位置。 ... -d选项导致shell忘记每个名称的记忆位置。

通过将不存在的文件传递给-p选项,就好像无法找到命令一样(尽管仍然可以通过完整路径访问它)。 传递-d撤消效果。

$ hash -p /dev/null/git git
$ git --version
bash: /dev/null/git: command not found
$ /usr/bin/git --version
git version 1.9.5
$ hash -d git
$ git --version
git version 1.9.5

添加一个名为git的函数

git() { false; }

这将“隐藏”git命令

要复制@ npostavs的想法,你仍然可以使用内置command获得“真正的”git:

command git --version

由于我们知道程序在bash中运行,因此一种解决方案是 - 而不是“隐藏”程序 - 在这种情况下模拟bash的行为。 我们可以很容易地找到bash在找不到命令时的作用:

$ bash
$ not-a-command > stdout 2> stderr
$ echo $?
127
$ cat stdout
$ cat stderr
bash: not-a-command: command not found

然后,我们可以将此行为写入具有可执行文件名的脚本,例如问题示例中的git

$ echo 'echo >&2 "bash: git: command not found" && exit 127' > git
$ chmod +x git
$ PATH="$PWD:$PATH" git
$ echo $?
127
$ cat stdout
$ cat stderr
bash: git: command not found

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM