Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

windows - What is the proper way to test if a parameter is empty in a batch file?

I need to test if a variable is set or not. I've tried several techniques but they seem to fail whenever %1 is surrounded by quotes such as the case when %1 is "c:some path with spaces".

IF NOT %1 GOTO MyLabel // This is invalid syntax
IF "%1" == "" GOTO MyLabel // Works unless %1 has double quotes which fatally kills bat execution
IF %1 == GOTO MyLabel // Gives an unexpected GOTO error.

According to this site, these are the supported IF syntax types. So, I don't see a way to do it.

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command

UPDATE: on 2020-10-25, I updated the accepted answer from using brackets to using a tilde. Everyone says the tilde is better as it's more secure. I'm a little torn cause the tilde looks more complicated and is less clear as to what it's purpose is but nevertheless, I changed it.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use square brackets instead of quotation marks:

IF [%1] == [] GOTO MyLabel

Parentheses are insecure: only use square brackets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...