2

I need to check whether a file is created and locked or not, using a batch file, if the file is locked the program should wait and check periodically whether the file is released from lock, and when it gets unlocked the program should exit.

I am very new to writing batch files (started today)

This is what I have tried:

@echo off
:loop
if (2<nul (>>test.txt echo off))(
    goto END
)
else (goto MESSAGE)
:MESSAGE
echo trying to access file
goto loop
:END
pause
Mark
  • 3,609
  • 1
  • 22
  • 33
user2907999
  • 175
  • 1
  • 1
  • 5
  • If you've just started, and you have some flexibility, I'd suggest using [tag:PowerShell], instead. – David Oct 22 '13 at 16:38
  • What are the results when you run this? Are you getting an error? If so, edit your question and add the error. If not, what are the results? – Theresa Oct 22 '13 at 16:39
  • I assume you mean a Windows batch file, and not DOS. – dbenham Oct 22 '13 at 16:45

1 Answers1

2

You were close :) But you cannot use IF to directly test whether a command succeeded or not. Use the || conditional operator instead.

Assuming you mean Windows, and not DOS:

@echo off
:loop
2>nul (
  (call ) >>test.txt
) || (
  echo Trying to access file
  timeout /nobreak 1 >nul
  goto loop
)

(call ) is simply a very efficient way to perform a no-op that always returns success.

The TIMEOUT introduces a 1 second delay to prevent the loop from hogging CPU resources.

See How to check in command-line if a given file or directory is locked (used by any process)? for more info on how the above works.

Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • hey, thanx a lot for the reply, but the 'timeout' was not recognized by the system so i modified that line by adding ping 1.1.1.1 -n 5 -w 3000 > nul now it works fine. Got it from here [link](http://stackoverflow.com/questions/1672338/how-to-sleep-for-5-seconds-in-windowss-command-prompt-or-dos) – user2907999 Oct 23 '13 at 07:10