Page 1 of 1

If Statement for Text Not Working

Posted: 02 Mar 2020 09:22
by logistician
Hello,

I'm trying to perform certain actions based upon the last character of a string. In my example below, the first if statement is never entered and I'm at a loss as to why. The code for getting the last character of a string I took from this website. Anybody have any thoughts?

Code: Select all

@echo off

set LOCAL_FILE_DIR=C:\test

echo\%LOCAL_FILE_DIR%

set tempstr=%LOCAL_FILE_DIR:~-1% & rem Get last character in string.

echo\%tempstr%

if "%tempstr%" == "t" (
	echo First if statement entered
)

set tempstr=t

if "%tempstr%" == "t" (
	echo Second if statement entered
)

pause
Output:

C:\test
t
Second if statement entered
Press any key to continue . . .

Re: If Statement for Text Not Working

Posted: 02 Mar 2020 11:06
by Aacini
In this line you entered a space between the last character and the & command separator:

Code: Select all

set tempstr=%LOCAL_FILE_DIR:~-1% & rem Get last character in string.
                    right here: ^
... so tempstr contains "t+space" and when you compare: if "%tempstr%" == "t" ( it is NOT true...

In order to avoid this type of problems, you always should delimit strings between quotes in set commands this way:

Code: Select all

set "tempstr=%LOCAL_FILE_DIR:~-1%" & rem Get last character in string.
Antonio

Re: If Statement for Text Not Working

Posted: 02 Mar 2020 12:12
by logistician
Thank you.