Testing for file attribute in batch file
Asked Answered
H

2

9

I'm writing a batch file and I need to know if a file is read only. How can I do that ?

I know how to get them using the %~a modifier but I don't know what to do with this output. It gives something like -ra------. How can I parse this in batch file ?

Hatching answered 20/5, 2009 at 14:27 Comment(2)
What kind of batch file ? bash, DOS ... ?Replevy
Windows batch files, as you can see from him mentioning %~a.Phosgene
C
13

Something like this should work:

@echo OFF

SETLOCAL enableextensions enabledelayedexpansion

set INPUT=test*

for %%F in (%INPUT%) do (
    set ATTRIBS=%%~aF
    set CURR_FILE=%%~nxF
    set READ_ATTRIB=!ATTRIBS:~1,1!

    @echo File: !CURR_FILE!
    @echo Attributes: !ATTRIBS!
    @echo Read attribute set to: !READ_ATTRIB!

    if !READ_ATTRIB!==- (
        @echo !CURR_FILE! is read-write
    ) else (
        @echo !CURR_FILE! is read only
    )

    @echo.
)

When I run this I get the following output:

File: test.bat
Attributes: --a------
Read attribute set to: -
test.bat is read-write

File: test.sql
Attributes: -ra------
Read attribute set to: r
test.sql is read only

File: test.vbs
Attributes: --a------
Read attribute set to: -
test.vbs is read-write

File: teststring.txt
Attributes: --a------
Read attribute set to: -
teststring.txt is read-write
Crissman answered 20/5, 2009 at 14:46 Comment(2)
Ok this is working for 1 file but if INPUT is a set, ATTRIBS will always have the same value. I tried setLocal EnableDelayedExpansion but it complains when I try to use !ATTRIBS:~1,1! What could I do ?Hatching
Thanks ! For some reason using !ATTRIBS:~1,1! directly in the comparison didn't work but storing it in another variable works.Hatching
P
7

To test a specific file:

dir /ar yourFile.ext >nul 2>nul && echo file is read only || echo file is NOT read only

To get a list of read only files

dir /ar *

To get a list of read/write files

dir /a-r *

To list all files and report whether read only or read/write:

for %%F in (*) do dir /ar "%%F" >nul 2>nul && echo Read Only:  %%F|| echo Read/Write: %%F

EDIT

Patrick's answer fails if the file name contains !. This can be solved by toggling delayed expansion on and off within the loop, but there is another way to probe the %%~aF value without resorting to delayed expansion, or even an environment variable:

for %%F in (*) do for /f "tokens=1,2 delims=a" %%A in ("%%~aF") do (
  if "%%B" equ "" (
    echo "%%F" is NOT read only
  ) else (
    echo "%%F" is read only
  )
)
Plosion answered 8/12, 2014 at 4:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.