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
3
  • If you've just started, and you have some flexibility, I'd suggest using powershell, instead. Commented Oct 22, 2013 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? Commented Oct 22, 2013 at 16:39
  • I assume you mean a Windows batch file, and not DOS. Commented Oct 22, 2013 at 16:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.