Home > database >  How can I loop through only .cpp files in the list obtained from "git status"
How can I loop through only .cpp files in the list obtained from "git status"

Time:07-07

I have a tool to analyse every .cpp file. I am implementing a pre-commit hook to analyse only edited and staged .cpp files in the local git repository before committing the changes. I have a shell script that gets called from the pre-commit hook and currently my following code fails to fetch me changed .cpp files. What is wrong with this script?

Code:

files=$(git status --porcelain | cut -b4-)
for file in $files; do
    if [$file == *.cpp]; then
        echo $file
    fi
done

Error:

./build_script.sh: line 23: [build_script.sh: command not found
./build_script.sh: line 23: [pre_commit_sqo_tmp/: No such file or directory

CodePudding user response:

Add spaces and use [[:

if [[ $file == *.cpp ]]; then

See man bash for the difference between [ and [[.

Also you can use

git ls-files -m "*.cpp"

This lists modified files with the given pattern. See https://git-scm.com/docs/git-ls-files . Please note the quotes — the pattern is screened to avoid the shell to interpret it; the pattern is passed to Git.

  • Related