0

I'm writting out some text to a text file within a cmd batch script like such:

echo FlagValue=Y>>flag.txt

This normally works fine but occassionally if the text file is open by a different process, an error messgae is returned saying Access Denied. What I'd like to do is stop the batch file if an error occurs with something like:

if return_code GEQ 1 GOTO ERR

But can't find a return code from echo command. Does one exist, or is there a better tactic to use to capture error message?

Tadhg
  • 193
  • 1
  • 3
  • 20

2 Answers2

2
echo FlagValue=Y>>flag.txt || echo access_denied Ensure you have rights

or

echo FlagValue=Y>>flag.txt
if /i %errorlevel% NEQ 0 do (
  echo access_denied Ensure you have rights
  call sendmail.cmd
)

Sample:

C:\Users\Me\Desktop>echo Hello > MyFile.txt || echo ERROR
Access is denied.
ERROR

C:\Users\Me\Desktop>echo Hello > a.txt || echo ERROR

C:\Users\Me\Desktop>
Stephan
  • 41,764
  • 65
  • 238
  • 329
Nicolas
  • 21
  • 2
0

Everytime you run a command the ERRORLEVEL environment variable is set to your command's return. So try echo %ERRORLEVEL% straight after you run your command. (Be careful as any command you run inbetween (including echo) will override the %ERRORLEVEL%.

Also, check these out for more information:
Can a batch file capture the exit codes of the commands it is invoking?
Batch Files - Error Handling

Community
  • 1
  • 1
Joe
  • 11,147
  • 7
  • 49
  • 60
  • I tried building a little test script echo off echo testline>>file1.txt echo errorlevel=%ERRORLEVEL% but result I got back was The process cannot access the file because it is being used by another process. errorlevel=0 – Tadhg Feb 28 '11 at 11:04
  • what error level do you get when you **can** access the file? i.e try to write to another file file2.txt – Joe Feb 28 '11 at 11:07
  • I still get errorlevel=0 regardless whether I can write to the file or not – Tadhg Feb 28 '11 at 11:55