Windows Batch syntax - Meaning of a colon in a variable's name

FabD picture FabD · Nov 22, 2015 · Viewed 9.3k times · Source

I have a .bat file that I need to convert into a linux .sh one.

In this .bat script there si some piece of code I just do not understand and I cannot find proper keywords to search it's meaning.

Here is the code:

if not x%VERSION:SNAPSHOT=%==x%VERSION% (
        echo " ....  SNAPSHOT version detected "
        echo VERSION=%VERSION:SNAPSHOT=%%formatdate%_%formattime%
    )

My main problem lies with the usage of a ":". What does %VERSION:SNAPSHOT=% do?

I also do not know the meaning of the 'x' in x%VERSION% or x%VERSION:SNAPSHOT%.

Could anybody help me to understand this please?

Answer

SomethingDark picture SomethingDark · Nov 22, 2015

The : (as well as the = at the end of the variable) are used for string substitution.

In this case, %VERSION:SNAPSHOT=% says to take the contents of the variable %VERSION% and replace any instance of the string SNAPSHOT with nothing.

As Mike said in the comments, the x on both sides is used to prevent a syntax error in case %VERSION% contains nothing but the string SNAPSHOT, which would cause a syntax error. Traditionally, you'll see quotes being used instead of other strings, but this method is perfectly valid.

The entire if statement checks to see if VERSION contains the substring SNAPSHOT and runs its code if it does.