How to "hide" an executable from a bash script?

I want to test the output of a bash script when one of the executable files on which it depends is missing, so I want to run the script with a dependent "hidden", but not with the others. PATH= ./script not an option, as the script must run other executables before it reaches the instruction I want to check. Is there a way to β€œhide” the executable from a script without changing the file system?

For a specific example, I want to run this script , but hide the git executable (which is its main dependency) so that I can check its output under these conditions.

+6
source share
3 answers

You can use the hash builtin command:

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

Each time hash is called, it remembers the full path names of commands specified as name arguments, so they do not need to be searched for on subsequent calls .... The -p option prevents the path from being searched, and the file name is used as the location of the name .... -d makes the shell forget the remembered location of each name.

By skipping a nonexistent file in the -p option, it will look as if the command could not be found (although you can still get the full path to it). Passing -d cancels the effect.

 $ 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 
+6
source

Add a function called git

 git() { false; } 

This will "hide" the git command

To copy the idea of ​​@npostavs, you can still get to the β€œreal” git using the built-in command :

 command git --version 
+4
source

Since we know that the program works in bash, one solution - instead of "hiding" the program - is to emulate the behavior of bash in this case. We can find out what bash does when a command is not found quite easily:

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

Then we can write this behavior in a script with an executable name, for example git in the example:

 $ 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 
+1
source

Source: https://habr.com/ru/post/989886/


All Articles