简体   繁体   English

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

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

I want to test the output of a bash script when one of the executables it depends on is missing, so I want to run that script with the dependency "hidden" but no others. 我想测试bash脚本的输出,当它依赖的其中一个可执行文件丢失时,所以我想运行该脚本的依赖项“隐藏”而不是其他。 PATH= ./script isn't an option because the script needs to run other executables before it reaches the statement I want to test. PATH= ./script不是一个选项,因为脚本在到达我想要测试的语句之前需要运行其他可执行文件。 Is there a way of "hiding" an executable from a script without altering the filesystem? 有没有一种方法可以在不改变文件系统的情况下从脚本中“隐藏”可执行文件?

For a concrete example, I want to run this script but hide the git executable (which is its main dependency) from it so that I can test its output under these conditions. 举一个具体的例子,我想运行这个脚本但是从它隐藏git可执行文件(这是它的主要依赖项),以便我可以在这些条件下测试它的输出。

You can use the builtin command, hash : 你可以使用builtin命令, hash

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

Each time hash is invoked, it remembers the full pathnames of the commands specified as name arguments, so they need not be searched for on subsequent invocations. 每次调用哈希时,它都会记住指定为名称参数的命令的完整路径名,因此无需在后续调用中搜索它们。 ... The -p option inhibits the path search, and filename is used as the location of name. ... -p选项禁止路径搜索,filename用作名称的位置。 ... The -d option causes the shell to forget the remembered location of each name. ... -d选项导致shell忘记每个名称的记忆位置。

By passing a non-existent file to the -p option, it will be as if the command can't be found (although it can still be accessed by the full path). 通过将不存在的文件传递给-p选项,就好像无法找到命令一样(尽管仍然可以通过完整路径访问它)。 Passing -d undoes the effect. 传递-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

Add a function named git 添加一个名为git的函数

git() { false; }

That will "hide" the git command 这将“隐藏”git命令

To copy @npostavs's idea, you can still get to the "real" git with the command builtin: 要复制@ npostavs的想法,你仍然可以使用内置command获得“真正的”git:

command git --version

Since we know the program is running in bash, one solution is to - instead of "hiding" the program - emulate the behaviour of bash in this circumstance. 由于我们知道程序在bash中运行,因此一种解决方案是 - 而不是“隐藏”程序 - 在这种情况下模拟bash的行为。 We can find out what bash does when a command isn't found quite easily: 我们可以很容易地找到bash在找不到命令时的作用:

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

We can then write this behaviour to a script with the executable name, such as git in the question's example: 然后,我们可以将此行为写入具有可执行文件名的脚本,例如问题示例中的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