Ajay Kumar
Ajay Kumar

Reputation: 3250

Windows batch script failed condition exit error message

I am trying to convert one of my bash(.sh) script into windows batch(.bat) script.

I am dealing with windows batch scripting for the first time. Got all the help from various SO threads and able to achieve what I needed except one, the following.

I need to exit on a condition where if a directory does not exist, exit the script. I took help from this thread - Best practice for exiting batch file?

Here is what I am came up with:

@echo off

set BACKUP_PARENT_DIR=C:\some\path\on\machine

if not exist %BACKUP_PARENT_DIR% (echo "Error Occurred..." exit /b 1) else (echo "All Good...")

echo "More Statements..."

else block/condition works fine but I get this as output of if condition:

"Error Occurred..." exit /b 1
"More Statements..."

Also it DOES NOT exit. It continues to run further.

What I want the output to look like is:

"Error Occurred..."

Question: What should I do in order to exit completely from the script execution and get rid of exit /b 1 from the failed condition of the 'if' block in the output printed on the command prompt?

Upvotes: 0

Views: 1189

Answers (1)

Stephan
Stephan

Reputation: 56155

echo "Error Occurred..." exit /b 1 echoes the literal string
"Error Occurred..." exit /b 1 instead of echoing just Error Occurrred... and actually exiting the script.

To execute two commands in the same line, use &, && or ||.

& means "and then execute ..."
&& means "if successful, then execute ..."
|| means "if unsuccessful, then execute ..."

Compare the output of the following four lines (Also try with an existing file):

dir nonexistent.file & echo finished
dir nonexistent.file && echo found it
dir nonexistent.file || echo no such file
dir nonexistent.file && echo found it || echo no such file

Also (unlike many other languages), batch's echo doesn't use quotes around the argument. They will just be part of the echoed string.

Upvotes: 1

Related Questions