Reputation: 362
I am new batch script. This could be a silly question. Can some one help me with following command.
when i run the following command. it works fine.
c:\test>git for-each-ref refs/tags --sort=-taggerdate --format=%(refname)
Output is : refs/tags/SAMPLE
Now I want to assign this output to variable
Trying to assign the value to TAG variable , but getting error.
C:\test>for /f %i in ('git for-each-ref refs/tags --sort=-taggerdate --format=%(refname)' ) do set TAG=%i
' was unexpected at this time.
Please help
Upvotes: 1
Views: 3143
Reputation: 3996
Here's a full example of a bat file I use to get information about my project. There are some other options but I find this one to be the most readable and keeps the intent of the script as close as possible to what would be done on the cmd line.
Put this file in your path env variable and you can run it for any project you have locally.
This file is checked in here: https://github.com/NACHC-CAD/bat/tree/main/files
@echo off
echo.
echo.
echo ------
echo Cloned from:
git config --get remote.origin.url
echo ------
echo.
echo ------
:: get the branch
git rev-parse --abbrev-ref HEAD > temp.txt
set /p branch=<temp.txt
echo Branch: %branch%
:: get the date
git show -s --format=%%ci > temp.txt
set /p date=<temp.txt
echo Date: %date%
:: get the hash
git show -s --format=%%H > temp.txt
set /p sha=<temp.txt
echo SHA: %sha%
:: clean up
del temp.txt
:: done
echo ------
echo.
echo.
echo Done.
echo.
echo.
Output is here:
D:\_WORKSPACES\_ECLIPSE_WORKSPACE\workspace\bat>where-am-i-really
------
Cloned from:
https://github.com/NACHC-CAD/bat
------
------
Branch: main
Date: 2022-05-12 14:40:03 -0400
SHA: 6fc95b29192fd65b2b16574ece6f20ba64ab1b59
------
Done.
D:\_WORKSPACES\_ECLIPSE_WORKSPACE\workspace\bat>
Upvotes: 0
Reputation: 229342
The parenthesis in --format=%(refname)
causes issues with the outer parenthesis, so you need to escape them, which is done with the ^
character.
for /f %i in ('git for-each-ref refs/tags --sort=-taggerdate --format=%^(refname^)' ) do set TAG=%i
Note 1: Do yourself a favor and use git-bash or powershell to script git on windows.
Note 2: There's many corner cases and differences depending on whether you run batch commands from a .bat fil or typing them into a console, see also Assign output of a program to a variable and Escaping parentheses within parentheses for batch file
Upvotes: 1