Reputation: 85
I am trying to send a command to Git Bash terminal through Autohotkey but unable to find a way to read its output. Is there a simple way for it? I am sending this
Run, C:\Users\Unknown\AppData\Local\Programs\Git\git-bash.exe
sleep, 2000
Send cd /c/Users/Unknown/Desktop/git/fw{Enter}
sleep, 1000
Send git log --pretty=format:'`%h' -n 1{Enter}
The answer to this is a commit number displayed on terminal
How can I read it?
Thanks
Upvotes: 3
Views: 1285
Reputation: 26296
To capture the output from a command, you can use one of the following RunWaitOne()
functions.
Option 1: Doesn't use a temporary file and can't hide the command window. (Source)
; From https://www.autohotkey.com/docs/commands/Run.htm#Examples
RunWaitOne(command) {
shell := ComObjCreate("WScript.Shell")
exec := shell.Exec(ComSpec " /C """ command """") ; change: added '"' around command
return exec.StdOut.ReadAll()
}
Option 2: Uses a temporary file and the command window is hidden. (Released under WTFPL)
RunWaitOne(command) {
tmpFile := A_Temp . "\" . A_ScriptName . "_RunWaitOne.tmp"
RunWait, % ComSpec . " /c """ . command . " > """ . tmpFile . """""",, Hide
FileRead, result, %tmpFile%
FileDelete, %tmpFile%
return result
}
I personally don't like hard coding in paths, so the following answer is set up to do the following steps:
GIT_BIN_DIR
GIT_BIN_DIR
result
.Code is released under WTFPL
; STEP 1: Try to find Git on PATH
EnvGet, E_PATH, PATH
GIT_BIN_DIR := ""
for i, path in StrSplit(E_PATH, ";")
{
if (RegExMatch(path, "i)Git\\cmd$")) {
SplitPath, path, , parent
GIT_BIN_DIR := parent . "\bin"
break
}
}
; STEP 2: Fallback to default install directories.
if (GIT_BIN_DIR == "") {
allUsersPath := A_ProgramFiles . "\Git\bin"
currentUserPath := A_AppData . "\Programs\Git\bin"
if (InStr(FileExist(currentUserPath), "D"))
GIT_BIN_DIR := currentUserPath
else if (InStr(FileExist(allUsersPath), "D"))
GIT_BIN_DIR := allUsersPath
}
; STEP 3: Show error Git couldn't be found.
if (GIT_BIN_DIR == "") {
MsgBox 0x1010,, Could not find Git's 'bin' directory
ExitApp
}
; STEP 4 - Queue any commands.
; commands becomes "line1 & line2 & ..." thanks to the Join continuation section
commands := "
(Join`s&`s
cd /c/Users/Unknown/Desktop/git/fw
git log --pretty=format:'`%h' -n 1
)"
; STEP 5 - Execute the commands (Uses "Git\bin\sh.exe" so we can capture output)
result := RunWaitOne("""" . GIT_BIN_DIR . "\sh.exe"" --login -i -c """ . commands . """")
; STEP 6 - Show the result
MsgBox 0x1040,, % result
Upvotes: 2