If not exists command in batch file

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

The interested part of this script should create a folder if this folder does not already exist , 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 am doing this correctly.

thanks

+9
source share
3 answers
 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 almost done everything. The logic is correct, only some small changes.

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

If it does not exist, it is created and the creation status is checked. If a file with the same name exists or you do not have permission to create a folder, it does not work.

If everything is correct, the files are copied.

All paths are quoted to avoid problems with spaces.

This can be simplified (just less code, this does not mean that it is better). Another option is to always try to create a folder. If there are no errors, 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 unless a folder is created at runtime.

EDITED - as the dben writes, the same code can be written as one line

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

The code after && will only be executed if the previous command did not set the error level. If mkdir does not work, xcopy not executed.

+15
source

When testing directories, remember that each directory contains two special files.

One is called '.' and another ".."

. is the directoryโ€™s own name as well . is the name of the parent directory.

To avoid backslash issues, just check to see if the directory recognizes its own name.

eg:

 if not exist %temp%\buffer\. mkdir %temp%\buffer 
+3
source
 @echo off if not exist "D:\Temp\"( md "D:\Temp\" ) ELSE ( echo Directory exists. Moving on... ) IF EXIST "D:\temp\test1.txt" ( ren "C:\temp\test1.txt" test1.txt~ move "C:\temp\test1.txt~" "D:\temp\" ) ELSE ( move "C:\temp\test1.txt" "D:\temp\" ) 
0
source

Source: https://habr.com/ru/post/969514/


All Articles