How do I write a batch file which opens the GitBash shell and runs a command in the shell?
Asked Answered
R

6

53

I'm on Windows 7 trying to use a batch file to open the GitBash shell and make a git call. This is the contents of my batch file:

REM Open GitBash 
C:\Windows\SysWOW64\cmd.exe /c ""C:\Program Files (x86)\Git\bin\sh.exe" --login -i"
REM retrieve archive
git archive master | tar -x -C %~1
REM quit GitBash
exit

I noticed that the GitBash is logging out before the next command "git archive...". Does anybody know if I can pass the command into GitBash and how?

Mike

Reducer answered 5/3, 2011 at 12:10 Comment(0)
S
70
"C:\Program Files (x86)\Git\bin\sh.exe" --login -i -c "git archive master | tar -x -C $0" "%~1"
Stethoscope answered 5/3, 2011 at 12:45 Comment(4)
Actually, I have another issue. I'm calling this command from the /build/ folder in my repo, so it only retrieves what's in the /build/ directory in the master. Is there someway to specify I want it to archive from the parent directory?Reducer
I needed to call an alias from a batch file and I used this answer to come up with: "C:\Program Files (x86)\Git\bin\bash.exe" --login -i -c "myaliasname" It worked perfectly! Thanks!Pronouncement
Is it possible to call multiple commands this way? (I try to make an executable from a git hook with wsh, but it creates a new thread for each command...)Leannaleanne
This variation (see end of comment) also includes a change directory after opening GIT because I have different directories to work with. I would just use "cd myDir" in the batch file but I'm using UNC paths (eg \\server01\myfolder) and those don't work with the cd command in the normal windows cmd.exe environment. "C:\Program Files\Git\git-bash.exe" --cd="\\Server01\projects\R_Code" -c "git commit -m'scheduled commit'"Gaullism
P
15

You can also run a shell script to run multiple commands

#! /bin/bash
cd /c/GitRepo/PythonScripts
git status
read -p "Press enter to continue"

then call that from your cmd line:

"c:\Program Files (x86)\Git\bin\sh.exe" --login -i -c "/c/GitRepo/PythonScripts/statusandwait.sh"
Photomontage answered 18/1, 2014 at 3:9 Comment(0)
L
7

In windows I created a git.bat file, and associated it to the .hook extension.

if not exist %1 exit
set bash=C:\Program Files (x86)\Git\bin\bash.exe
"%bash%" --login -i -c "exec "%1""

After that you can run the .hook files like every .bat or .cmd file except that they are running under git shell...

Leannaleanne answered 15/2, 2012 at 2:4 Comment(3)
Hi @inf3rno, a rather late comment, but it would be good if you can elaborate more on the "associated it to the .hook extension". Thanks.Meprobamate
@Meprobamate Just google "Windows file associations".Leannaleanne
Hi @inf3rno, my point was that your answer should not lead me to further googling ;-), Anyways, thanks for your pointer.Meprobamate
A
1

Use Bash is more friendly, for example

# file: backup.sh

cd /c/myProyectPath/
PWD=$(pwd);

function welcome() {
   echo "current Dir   : $PWD";
}

function backup() {
   git pull

   #if you have install wamp <http://www.wampserver.com>, we making slqBackup
   MYSQLDUMP="/c/wamp/bin/mysql/mysql5.6.12/bin/mysqldump.exe";
   $MYSQLDUMP --user=login --password=pass --no-create-info bd > data/backup.sql
   git add data/backup.sql;

   #generating tar file
   git archive -o latest.tar HEAD
}

welcome;
backup;

echo "see you";
sleep 30;

You can run the script:

"C:\Program Files (x86)\Git\bin\sh.exe" --login -i -c "/c/myProyectPath/run.sh"
Apatetic answered 7/3, 2014 at 2:3 Comment(0)
M
1

After a lot of trials , I got this one working. With current version of Git For Windows Portable. Open a Windows command window, and execute this script. If there is a change in your working directory, it will open a bash terminal in your working directory, and display the current git status. It keeps the bash window open, by calling exec bash.

If you have multiple projects you may create copies of this script with different project folder, and call it from a main batch script.

Update - check new added files , that is untracked files.

=============

REM check git status of given folders. 

setlocal EnableDelayedExpansion

set GIT_HOME=D:\eclipse\devtools\PortableGit-2.6.2

set GIT_EXEC=%GIT_HOME%\mingw64\bin\git.exe
set GIT_BASH=%GIT_HOME%\bin\bash.exe

set GITREPO=D:\source\myproject

pushd %GITREPO%
%GIT_EXEC% status
%GIT_EXEC%  diff-index --quiet --cached HEAD
set VAR1=%errorlevel%
if not "%VAR1%"=="0" (
echo.
echo There are changes which are staged i.e. in index - but not committed.
echo.
)
%GIT_EXEC% diff-files --quiet
set VAR2=%errorlevel%
if not "%VAR2%"=="0" (
echo.
echo There are changes in working directory.
echo.
)

rem below for loop requires enabledDelayedExpansion
for /f "delims=" %%i in ('%GIT_EXEC% ls-files --others --exclude-standard') do (
    if "!VAR3!"=="" (set VAR3=%%i) else (set VAR3=!VAR3!#%%i)
)

if not "%VAR1%"=="0" set REQUIRECOMMIT=true
if not "%VAR2%"=="0" set REQUIRECOMMIT=true
if not "%VAR3%"=="" set REQUIRECOMMIT=true

if "%REQUIRECOMMIT%"=="true" (
    start "gitbash" %GIT_BASH% --login -i -c "git status; exec bash"
)

popd

endlocal
Malvina answered 27/10, 2015 at 12:28 Comment(1)
Thank you thank you thank you! This will help me get my started a little faster.Hendon
I
0

In my case, a certain HTTP Request would work in curl within Git Bash on Windows. However, I would get a Connection Reset error when running on Java using HttpClient and HttpGet (org.apache.http.client.methods.HttpGet).

If I tried to use exec to directly run the command, for some reason it would not work.

As a workaround, this code will write the command in a batch file, then run the batch file and place the output in command.txt.

Here is the command which needs to be in the command.bat file (I have changed the endpoint and password):

"C:\Users\scottizu\AppData\Local\Programs\Git\bin\sh.exe" --login -i -c "curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt"

Here is the code (notice the command has special characters escaped):

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class CURL_Runner {
    public static void main (String[] args) throws Exception {
        String command = "\"C:\\Users\\scottizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe\" --login -i -c \"curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt\"";
        createAndExecuteBatchFile(command);
    }

    public static void createAndExecuteBatchFile(String command) throws Exception {

        // Step 1: Write command in command.bat
        File fileToUpload = new File("C:\\command.bat");
        try {
            if(fileToUpload.getParentFile() != null && !fileToUpload.exists()) {
                fileToUpload.getParentFile().mkdirs();
            }
            FileWriter fw = new FileWriter(fileToUpload);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(command);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Step 2: Execute command.bat
        String[] cmdArray = new String[1];
        cmdArray[0] = "C:\\command.bat";

        Process process = Runtime.getRuntime().exec(cmdArray, null, new File("C:\\"));
        int processComplete = process.waitFor();
    }
}
Inclining answered 7/7, 2017 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.