25
votes

I need to write some code in a windows batch file.

The interested part of this script should create a folder if this folder doesn't exist yet, but, if this folder already exists, it should NOT overwrite the content.

I tried something like this:

if not exist %USERPROFILE%\.qgis-custom (
    mkdir %USERPROFILE%\.qgis-custom 
    xcopy %OSGEO4W_ROOT%\qgisconfig %USERPROFILE%\.qgis-custom /s /v /e
)

But I'm not sure if I'm doing it right.

Thank you

2
If the folder exist, it should not be overwritten, but should any aditional file be copied? That is, files in source (OSGEO4W_ROOT) not already present in target (USERPROFILE).MC ND
no, I'd say no. Directory should remain as it is.matteo

2 Answers

31
votes
if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

4
votes

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer