If Statement for Text Not Working

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
logistician
Posts: 4
Joined: 02 Mar 2020 09:18

If Statement for Text Not Working

#1 Post by logistician » 02 Mar 2020 09:22

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 . . .

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: If Statement for Text Not Working

#2 Post by Aacini » 02 Mar 2020 11:06

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

logistician
Posts: 4
Joined: 02 Mar 2020 09:18

Re: If Statement for Text Not Working

#3 Post by logistician » 02 Mar 2020 12:12

Thank you.

Post Reply