Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a file/dir is writable in batch scripts

In bash, I would use

[ -w ... ]

What's the equivalent for Windows batch files?

like image 542
Marc Mutz - mmutz Avatar asked Jan 04 '10 14:01

Marc Mutz - mmutz


2 Answers

Sorry folks for chiming in here..

This may not be 100% what you are looking for, but I have used this with in-use log files for Apache Tomcat and it works absolutely perfectly.

Thanks to @dbenham for his awesome code! https://stackoverflow.com/a/10520609/175063

SETLOCAL ENABLEDELAYEDEXPANSION
REM TOMCAT LOGS
FOR /r "D:\logs" %%X IN (*) DO (
    SET FileName=%%~nxX
    2>nul (   >>D:\logs\!FileName!" (call )) && (
    REM DO STUFF HERE
    SET ModDt=%%~tX
    FOR /f "tokens=1-3 delims=.:/ " %%j IN ("!ModDt!") DO SET FDate=%%l-%%j-%%k&Set RegDate=%%j-%%k-%%l
    IF "%CurrentDate%" NEQ "!FDate!" (
        IF %%~zX GTR 0 (
            ECHO ARCHIVING "D:\logs\!FileName!" >> %logfile%
            7za.exe -tzip -y a "D:\Zips\%COMPUTERNAME%-Tomcat-!RegDate!-compressed.zip" "D:\logs\!FileName!" && (
            DEL /Q "D:\logs\!FileName!"
            ) || (
                if "%ERRORLEVEL%" == "2" (
                    echo Zipping failed ^(exit status %ERRORLEVEL%^).  Trying again in 5 seconds...
                ) else (
                    echo Zip completed with warnings ^(most likely because a file was locked by another
                    echo process and had to be skipped^).  Trying again in 5 seconds...
                )
                del "D:\Zips\%COMPUTERNAME%-Tomcat-!RegDate!-compressed.zip" >NUL 2>&1
                PING 0.0.0.0 -n 6 -w 1000 >NUL
            )
        )
    )
    REM END OF UNLOCKED ZONE
    ) || (
    ECHO FILE IS LOCKED
    )
)
like image 30
Leptonator Avatar answered Sep 28 '22 06:09

Leptonator


As far as I know, you can find out whether the file exists or not, but there's no way to know if it's writeable, apart from trying to write on it. It's not only a matter of not having the R flag; network and NTFS permissions are involved as well (and probably group policies too).

If you can rewrite your code, you can capture the return code of the write operation trough the errorlevel.

like image 74
Álvaro González Avatar answered Sep 28 '22 08:09

Álvaro González