首页 > 解决方案 > trying to set a value to a variable in batch

问题描述

i'm trying to write a simple script to do git add, commit and push.

@echo off
SET operation=%1
SET opParam=%2
SET mainBranch=dev/1.1

if %operation%==fire (
    for /f %%i in ('git rev-parse --abbrev-ref HEAD') do set branchName=%%i
    if %opParam%.==. (
        SET opParam="autogeneratedmessage"
        @echo on
        echo %opParam%
        @echo off
    ) else (
        SET opParam="%opParam%"
        @echo on
        echo %opParam%
        @echo off
    )
    git add -A 
    git commit -m %opParam%
    git push origin %branchName%
)

So the problem is when the second parameter is empty, it fails to set the value of opParam to autogeneratedmessage at line 9.

Here is what i have tried so far to set the opParam:

SET opParam=""autogeneratedmessage""
SET opParam="autogeneratedmessage"
SET "opParam=autogeneratedmessage"

I really can't see what im doing wrong here. It seems like a simple issue but i've been on this for half an hour now.

标签: batch-file

解决方案


I had enable the delayed expansion in that block and reference my variable using ! instead of %.

if %operation%==fire (
    setlocal enabledelayedexpansion
    for /f %%i in ('git rev-parse --abbrev-ref HEAD') do set branchName=%%i
    if %opParam%.==. (
        SET opParam="autogenerated"
        @echo on
        echo !opParam!
        @echo off
    ) else (
        SET opParam="%opParam%"
        @echo on
        echo %opParam%
        @echo off
    )
    git add -A 
    git commit -m !opParam!
    git push origin %branchName%
)

推荐阅读