Home > Mobile >  How can I send messages on every single command like "fatal: This operation must be run in a wo
How can I send messages on every single command like "fatal: This operation must be run in a wo

Time:05-10

In a .git folder, the message

fatal: This operation must be run in a work tree

in the title comes on my input such as ls, cd ., even echo hi and so on.

My question is NOT how to solve this or NOT asking why it comes out.

I want to send messages to users (on any commands) like this for my own purpose (when PWD is in a specified location such as /home/user_name/target if possible). How is it installed? My environment is macOS. (If I get any clues, I will find solutions on any other OSs)

(My question may not be related to Git)

CodePudding user response:

It's not (to me) clear why you would want this. The short answer is no, the bash, cshell, zsh, ksh, etc, do not have such a hook to make a call to a function and decide to not execute a command based on the return value of that function.

To do such a thing you would need your own shell (interpreter), and your code would perform the checks that you want to perform when your in the .git directory and print that message whenever you decide it needs to be printed.

Wrapping shell commands appears to be trivial, but full shell functionality is not. NOTE: Below was not tested

#!/bin/bash
while [ read line ]
do
   if inGitDir 
   then
      if [ $line != "pwd" ]
      then
          echo "fatal: This operation must be run in a work tree"
      else
          exec $line
      fi
done

This is only a play example, however, because real shell/interpreters handle multiple commands with redirection, sub-shells, terminal control groups, Suspend, Resume, etc.

If you wanted to do this (still) then look for the source for bash or your favorite shell and implement it. :-)

  • Related