Generate a warning when multiple executables are in transit when executing a command in bash

Say I have:

>which -a foo /bin/foo /usr/bin/foo 

I need something like:

 >foo Warning: multiple foo in PATH ... foo gets executed ... 

This functionality would save me a lot of time today. I should have guessed that this was happening earlier, but the problem was not clear to me at the beginning, and I began to delve into the completely opposite direction.

+6
source share
2 answers

Well, you can do it, but it's not as easy as you think.

First you need to create a function that will check all directories in the PATH, and look there for the command you are trying to run. Then you need to associate this function with the DEBUG trap of your current shell.

I wrote a small script that does this:

 $ cat /tmp/1.sh check_command() { n=0 DIRS="" for i in $(echo $PATH| tr : " ") do if [ -x "$i/$1" ] then n=$[n+1] DIRS="$DIRS $i" fi done if [ "$n" -gt 1 ] then echo "Warning: there are multiple commands in different PATH directories: "$DIRS fi } preexec () { check_command $1 } preexec_invoke_exec () { [ -n "$COMP_LINE" ] && return # do nothing if completing local this_command=`history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g"`; preexec "$this_command" } trap 'preexec_invoke_exec' DEBUG 

Usage example:

 $ . /tmp/1.sh $ sudo cp /bin/date /usr/bin/test_it $ sudo cp /bin/date /bin/test_it $ test_it Warning: there are multiple commands in different PATH directories: /usr/bin /bin Wed Jul 11 15:14:43 CEST 2012 $ 
+6
source

This is possible, although a little trick to generalize. See my answer at https://unix.stackexchange.com/q/42579/20437 for the history magic and PROMPT_COMMAND . The checkSanity function will look something like this:

 checkSanity() { cmd="${1%% *}" # strip everything but the first word candidates=$(which -a $cmd | wc -l) if (( candidates > 1 )); then echo "Warning: multiple $cmd in PATH" fi } 

But this will print a warning after the completion of the command, and not from the very beginning. Instead, use the DEBUG trap to get the desired result:

 trap 'checkSanity "$BASH_COMMAND"' DEBUG 
+2
source

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


All Articles