Home > Software engineering >  How to create a script to add, commit and push file by file a set of new or changed files?
How to create a script to add, commit and push file by file a set of new or changed files?

Time:10-26

I want to create a shell script that add, commit and push new or changed files to a repository. Currently, my script is doing this by iterating file by file, which takes too much time. My requirement is to still doing this file by file, but this time I just want to iterate over the new or changed files.

My shell script is as follows:

#!/bin/sh

CUR_DIR=$(pwd)
PROJECT_DIR="${CUR_DIR}"

for fileToCommit in $(find ${PROJECT_DIR}/* -type f);
do
  test -f "$fileToCommit" || continue
  printf "%s\n" "${fileToCommit}"
  git add "${fileToCommit}"
  git commit -a -m "[ADD] New ${fileToCommit##*/} File"
  git push
done

How can I do it in an effortless way?

CodePudding user response:

From the git status documentation:

--porcelain[=<version>]
    Give the output in an easy-to-parse format for scripts.
    This is similar to the short output,
    but will remain stable across Git versions and regardless of user configuration.

This is the intended way to gather all changed/untracked/deleted files for scripts. It will give you an easy to parse output, still allowing you to handle all files individually if desired.

Furthermore, I think it would be wise to look into what porcelain means in git terminology. It will help you write reliable scripts across different git versions.

What does the term "porcelain" mean in Git?

A small example of how you can use this:

filesToPush=$(git status --porcelain | awk '{print $2}')

for file in $filesToPush; do
    # Your actions.
done

This example considers that you want to do the same actions for all files returned by git status. If you want different behavior for different file statuses (changed, deletion, untracked), you will need to extract column 1 as well and change behavior dependent on this.

How to get the second column from command output?

  • Related