-2

Below is hook code I am using for pre-commit in VS 2019. I want to restrict some files being committed always. Trying with string.exe. But getting error. Help needed on this.

#!/bin/sh
#!/usr/bin/env bash
listchange=$(git diff --name-only) 

echo "Check filenames:"

wrongfilenames=$(
            for filename in $listchange 
            do
                fname= $filename
                if [[ $fname = 'strings.exe' ]]; then 
                    echo $fname;
                    echo "has strings.exe"
                fi
            done
        );
        
if [ -n "$wrongfilenames" ] ; then
echo "The following files need not to commit:"
echo "$wrongfilenames"
echo "Commit rejected, fix it and try again."
exit 1
else
echo "....OK"
torek
  • 448,244
  • 59
  • 642
  • 775

1 Answers1

2

It looks like you are missing a fi at the end of the conditional check.

#!/bin/bash
listchange=$(git diff --name-only) 

echo "Check filenames:"

wrongfilenames=$(
    for filename in $listchange 
    do
        if [[ "$filename" = "strings.exe" ]]; then 
            echo "$filename"
            echo "has strings.exe"
            # TODO: take the appropriate action(s) here
            return 1 # => quit with error
        fi
    done
);
        
if [ -n "$wrongfilenames" ] ; then
    echo "The following files need not to commit:"
    echo "$wrongfilenames"
    echo "Commit rejected, fix it and try again."
    exit 1
else
    echo "....OK"
fi

NOTE: it is a good practice to add double quotes around $var when checking content against string. Indeed, if the $var has white-spaces it will not work as expected.

Jib
  • 1,334
  • 1
  • 2
  • 12
  • Thanks , resolved that , but now it is committing code having string.exe in changes. What am I missing ? Also for testing I want to have array of file names in 'listchange'. How Can i ? – Hemant Pawar Oct 07 '22 at 09:51
  • It is because there is no action taken (yet) in case the file matches.. – Jib Oct 07 '22 at 09:57
  • Thanks job, I am new to bash script. Script is running ok on online editor. Need one favor, how can I see my pre-commit bash script's echos in visual studio. I am interested in what listchange=$(git diff --name-only) returns. rest things are working fine. – Hemant Pawar Oct 07 '22 at 12:25