Home > Blockchain >  Am i understanding this has_hook_script shell function correctly?
Am i understanding this has_hook_script shell function correctly?

Time:01-19

I've come across the following function in a React project shell script and am quite new to shell scripting so would like to confirm my understanding of it.

In simple english, is the function checking there is a package.json file and then reading that file, I'm not sure what the glob pattern is doing though. The function is being passed a precommit string, so would it match the following? it does seem a bit odd if it matches the 2nd one as well

"precommit":
"precommit"   abcde:

has_hook_script () {
        [ -f package.json ] && cat package.json | grep -q "\"$1\"[[:space:]]*:"
      }

CodePudding user response:

Basically the function checks the JSON to see if there is a key with the same name as the first argument passed to the function.

Breaking it down step by step:

[ -f package.json ]

Does "package.json" exist and is it a file?

&&

if so, then:

cat package.json |

pipe its contents to the following command:

grep -q

grep's quiet mode, which will look for a match with the following regular expression:

\"$1\"[[:space:]]*:

\"$1\" - the first argument passed to the function inside double quotes (which is why the the double quotes are escaped)

followed by [[:space:]]* - zero or more spaces (in a regex context, * means 0 or more of the character preceding it).

followed by a : - valid JSON can have 0 or more spaces between the key name and the colon

Since grep is the last command executed in the function, the function will test successfully if a matching key is found.

  •  Tags:  
  • Related