Nick Offenberger
Nick Offenberger

Reputation: 75

Batch if/else statements

I am currently writing a batch file to create, edit, and delete journal entries for an internship I'm currently working on, I don't seem to understand how to get my if/else statements to work, this is my first time using batch, most of the coding I have done has either been in Linux or Python, so maybe I'm just making a dumb mistake:

:edit
echo Welcome to the editing menu!
echo To edit a journal entry, enter the date of the journal below in a MM-DD-YYYY format! (I.E. 05-8-1982)
powershell sleep 3
set /p filename2=What is the date of the entry you are looking for?
echo Searching for file now... 
powershell sleep 1
if EXIST "%filename2%.txt" G:\Batch\JournalEntries\*
(
start "%filename2%.txt"
)
ELSE (
ECHO not found

From this point, when I run the program and get to the editing menu, I am asked to enter a filename. I put it in and then a new cmd window opens with the filename I've entered, as it is unable to find the name I entered (This is done on purpose, I am testing whether it will give me the else error or not).

Upvotes: 1

Views: 141

Answers (1)

double-beep
double-beep

Reputation: 5504

Your fixed code must look like:

:edit
echo Welcome to the editing menu!
echo To edit a journal entry, enter the date of the journal below in a MM-DD-YYYY format! (I.E. 05-8-1982)
timeout /T 3 >nul
set /p "filename2=What is the date of the entry you are looking for? "
echo Searching for file now... 
timeout /T 1 >nul
if exist "%filename2%.txt" (
    if exist "G:\Batch\JournalEntries\*" (
        start "" "%filename2%.txt"
    ) else (
        echo Did not found files matching pattern G:\Batch\JournalEntries\*!
    )
) else (
    echo Did not found files matching pattern %filename2%.txt!
)
pause

Just some notes:

  • There is a timeout command in batch: it is used to wait for a specified period. Alternative: ping.
  • Quote var and value when setting variables like set "var=value". Use the same format even if there are /a or /p options.
  • You seem to misunderstand the if command usage. At least one parenthesis should be in the same line as if; see the above code block for more details.
  • It is good not to write with upper-case in batch. It just makes noise as it is a case-insensitive language.
  • It seems you made a mistake quoting %filename2%.txt file quoting both filename and filename and extension. Since quotes aren't allowed as a file/foldername, I have removed and just double-quoted filename and extension.

For more information about the commands used, please type in cmd.exe:

  • echo /?
  • timeout /? explains its usage
  • ping /? alternative to timeout
  • if /? explains syntax and usage of if
  • start /?

Upvotes: 1

Related Questions