aizeenX
aizeenX

Reputation: 21

Git Push script in BASH

I am making a small automation to add all the .java files in my current directory but it has some flaws.

It pushes each file instead of pushing them all at once, it's okay If it asks the commit message for each file but I tried to git push the files outside the for loop.

#!/bin/bash
 
javafile=*.java
 
for i in $javafile;
do
        if [[ "$i" == "$javafile" ]]
        then
                echo "No .java files"
        else
                git add $i
                echo
                echo "File $i added"
                echo
                echo "Write a message to commit"
                read message
                git commit -m "$message"
                git push origin master
                echo
                echo "#############################################"
                echo "$i pushed successfully"
                echo "#############################################"
        fi
done

Upvotes: 0

Views: 841

Answers (1)

0stone0
0stone0

Reputation: 43962

The problem is the git push origin master inside the loop, consider the following script;

#!/bin/bash
 
javafile=*.java
filesCommit=0

# For each java file
for i in $javafile; do
    if [[ "$i" == "$javafile" ]]; then
        echo "No .java files"
    else
        # Add current file
        git add $i
        echo
        echo "File $i added"

        # Ask for commit message
        echo
        echo "Write a message to commit"
        read message

        # Commit single file with message
        git commit -m "$message"

        # Bumb counter to remember number of items
        ((filesCommit++))
    fi
done

# If we've had atleast 1 file, push
if [[ "$filesCommit" -ge 0 ]]; then
    git push origin master
    echo
    echo "#############################################"
    echo "Pushed successfully; $filesCommit files"
    echo "#############################################"
fi

Here I'm using a variable to count the number of files we've commited. Then, after the loop, we can push all those files

Upvotes: 3

Related Questions