Let’s say I already have a folder created on the next path file: "C:userscharqusdesktopMyFolder"
, and I run the next command on CMD:
mkdir "C:userscharqusdesktopMyFolder"
I get a message like this: «A subdirectory or file C:userscharqusdesktopMyFolder already exists».
Therefore, is there any command in the commandline to get rid of this returned messages?
I tried echo off but this is not what I looking for.
asked Nov 30, 2013 at 9:35
1
Redirect the output to nul
mkdir "C:userscharqusdesktopMyFolder" > nul
Depending on the command, you may also need to redirect errors too:
mkdir "C:userscharqusdesktopMyFolder" > nul 2> nul
Microsoft describes the options here, which is useful reading.
answered Nov 30, 2013 at 9:39
Roger RowlandRoger Rowland
25.8k11 gold badges72 silver badges113 bronze badges
4
A previous answer shows how to squelch all the output from the command. This removes the helpful error text that is displayed if the command fails. A better way is shown in the following example:
C:test>dir
Volume in drive C has no label.
Volume Serial Number is 4E99-B781
Directory of C:test
20/08/2015 20:18 <DIR> .
20/08/2015 20:18 <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 214,655,188,992 bytes free
C:test>dir new_dir >nul 2>nul || mkdir new_dir >nul 2>nul || mkdir new_dir
C:test>dir new_dir >nul 2>nul || mkdir new_dir >nul 2>nul || mkdir new_dir
As is demonstrated above this command successfully suppress the original warning. However, if the directory can not be created, as in the following example:
C:test>icacls c:test /deny "Authenticated Users":(GA)
processed file: c:test
Successfully processed 1 files; Failed processing 0 files
C:test>dir new_dir2 >nul 2>nul || mkdir new_dir2 >nul 2>nul || mkdir new_dir2
Access is denied.
Then as can be seen, an error message is displayed describing the problem.
answered Aug 7, 2015 at 13:07
user1976user1976
3534 silver badges15 bronze badges
Razvedka2020 40 / 35 / 9 Регистрация: 01.01.2014 Сообщений: 201 |
||||
1 |
||||
Как скрыть ошибку выполнения?22.02.2020, 22:15. Показов 13263. Ответов 8 Метки нет (Все метки)
Здравствуйте уважаемые форумчане. Решил навести красоту в своих скриптах и столкнулся с неприятностями, а именно с отображением ошибок (код импровизированный):
Вопрос: как можно избавится от отображения ошибок?
0 |
alpap 4332 / 2122 / 661 Регистрация: 26.04.2015 Сообщений: 6,823 |
||||
23.02.2020, 03:54 |
2 |
|||
1 |
Razvedka2020 40 / 35 / 9 Регистрация: 01.01.2014 Сообщений: 201 |
||||||||
23.02.2020, 05:45 [ТС] |
3 |
|||||||
Я может быть не понимаю ваш ответ, но в строке 3 я уже пробовал конструкцию (она не помогла и я ее закоментировал)
Это не помогает избавится от вывода ошибки, так же как и
Результат одинаков, на скриншоте.
0 |
6575 / 1776 / 303 Регистрация: 10.12.2013 Сообщений: 6,258 |
|
23.02.2020, 07:11 |
4 |
Решил навести красоту в своих скриптах И тут же воткнёшься носом в неразрешимое противоречие понятия красоты.
0 |
5851 / 2563 / 1007 Регистрация: 06.06.2017 Сообщений: 8,750 |
|
23.02.2020, 07:16 |
5 |
но в строке 3 я уже пробовал конструкцию А где там
0 |
Razvedka2020 40 / 35 / 9 Регистрация: 01.01.2014 Сообщений: 201 |
||||
23.02.2020, 07:20 [ТС] |
6 |
|||
А где там 2>nul спереди? Можно для особо «одаренных» пояснить что за
или где про это почитать?
0 |
6575 / 1776 / 303 Регистрация: 10.12.2013 Сообщений: 6,258 |
|
23.02.2020, 07:47 |
7 |
Решение Программная абстракция существования стандартных файловых потоков в виде их описателей (handles) Код ECHO "раз два три-пять зайтчик погулять" 1 > NUL 2 > &1 интерпретатор распознает сочетание 1 > NUL ( {одинокая цифра}
1 |
5851 / 2563 / 1007 Регистрация: 06.06.2017 Сообщений: 8,750 |
|
23.02.2020, 08:11 |
8 |
Решение
1 |
40 / 35 / 9 Регистрация: 01.01.2014 Сообщений: 201 |
|
23.02.2020, 08:14 [ТС] |
9 |
Большое вам всем человеческое спасибо. Не зря говорят: Век живи, век учись…
0 |
Thanks for your quick answers, i really appreciate.
Microsoft has been telling us for over a decade that PowerShell is the future of scripting.
I know indeed. I’m currently optimizing my own application in Batch+third party tools (a retrogame launcher, the main Batch script is about 41000 lines) by improving various stuffs here and there, so i guess Powershell will wait for a next project (smile). But anyway thanks for your advice, you’re right.
Alternatively you could use the same method to reset the read only attribute, write to the file, then apply the read only attribute again:
This dir /A:-DR /B
is nice and fast way to test if a file is read-only, indeed. There may be benefits to proceed in this way instead of 1. grabbing the file attribute with a more conventional for %%F in ("MyReadOnlyFile.txt") do set "file.attr=%%~aF"
then 2. testing the second character by enabling delayed expansion. I will check where i can use it in my code to optimize some parts slightly, thank you for your suggestion Compo.
The error isn’t written to STDERR, but to STDOUT (don’t ask me, why), so echo( >»MyReadOnlyFile.txt» 1>nul suppresses the error message (sadly along with any possible useful output)
Thanks for your answer Stephan. Well, we know that Batch is quite insane often, but a such behavior would be more than insanity (smile). Redirecting stdout 1>nul doesn’t hide the error message (as expected). However, surrounding the command and file redirection with brackets works as expected:
(echo( >"MyReadOnlyFile.txt") 2>nul
It might be a possible typing error on SS64 about the position of surrounding brackets, it should be (command >"filename") 2>nul
. The error message is redidrected to stderr as expected, confirmed by the following if you open the «stderr.txt» file.
(echo( >"MyReadOnlyFile.txt") 2>"stderr.txt"
Again thank you to have replied, i did read a ton of threads on stackoverflow during the whole development of my application but i never subscribed. So that’s a special feeling to have opened an account finally.
EDIT
I also add these two in case it can help someone.
rem Merge stderr to stdout.
set "_mute=>nul 2>&1" & set "_mute1=1>nul" & set "_mute2=2>nul"
rem Force ERRORLEVEL to 0.
set "_errlev0=(call )"
rem If you're lazy to type it each time (i am !).
set "_ede=enabledelayedexpansion"
rem Existing file name.
set "file.path=MyTestFile.txt"
rem Paths to the SQLite executable and SQLite database (example).
set "sqlite_file.path=C:SQLiteSQLite.exe"
set "db_file.path=C:DatabaseMyBase.db"
setlocal %_ede%
rem --- Test1 ---
%_errlev0%
echo ERRORLEVEL=!ERRORLEVEL!
(echo| set /p dummy_name="Hello & world">>"!file.path!") %_mute% && (
echo Test1 succeeded
) || (
echo Test1 failed
)
echo %ERRORLEVEL=!ERRORLEVEL!
rem --- Test2 ---
:: Whatever SQLite query of your choice.
set "sql_query=SELECT arcade_t.description FROM arcade_t WHERE arcade_t.description LIKE '%%Capcom%%'"
set "sql_bad_query=_!sql_query!"
%_errlev0%
echo ERRORLEVEL=!ERRORLEVEL!
(>>"!file.path!" "!sqlite_file.path!" "!db_file.path!" "!sql_query!") %_mute% && (
echo Test2 succeeded
) || (
echo Test2 failed
)
echo ERRORLEVEL=!ERRORLEVEL!
endlocal
-
Surrounding the WHOLE command
echo| set /p dummy_name="..."
with brackets (as mentionned above, cf typing error in the SS64 page) and muting both stdout+stderr (or stderr only with %_mute2%) will hide the error message if writing the file failed. -
Mentionning a variable name in the command
set /p dummy_name="..."
sets ERRORLEVEL as expected once the commandecho| set /p="..."
ends: 0 if writing the file succeeded, 1 if it failed. On the contrary, using a nameless commandecho| set /p ="..."
sets ERRORLEVEL to 1 even if writing the file succeeded, so should be avoided. -
Again, surrounding the WHOLE SQLite command with brackets will hide the «Acces is denied.» message but the SQLite «Error: near «_SELECT»: syntax error» error message as well in case the SQLite query is syntaxically incorrect. This has has been tested and confirmed by replacing the proper query with the bad one
sql_bad_query
.
Вывод на экран сообщения или задание режима вывода на экран сообщений команд. Вызванная без параметров команда echo выводит текущий режим.
Синтаксис
echo [{on|off}] [сообщение]
Параметры
- {on|off}
- Включение или отключения режима отображения на экране информации о работе команд.
- сообщение
- Задание текста для вывода на экран.
- /?
- Отображение справки в командной строке.
Примечания
- Команда echo сообщение может оказаться полезной, если отключен режим отображения работы команд. Для вывода сообщений из нескольких строк без вывода дополнительных команд между ними следует использовать несколько последовательных команд echo сообщение после команды echo off в пакетной программе.
- Если используется команда echo off, приглашение командной строки не отображается на экране. Чтобы отобразить приглашение, введите командуecho on.
- Чтобы отключить вывод строк, введите символ «коммерческого эт» (@) перед командой в пакетном файле.
- Чтобы вывести на экране пустую строку, введите следующую команду:
echo.
- Чтобы вывести символы канала (|) или перенаправления (< или >) при использовании команды echo, введите символ (^) непосредственно перед символом канала или перенаправления (например ^>, ^< или ^| ). Чтобы вывести символ (^), введите два этих символа подряд (^^).
Примеры
Следующий пример представляет собой пакетный файл, выводящий сообщение из трех строк на экран с пустыми строками до и после него:
echo off
echo.
echo Эта пакетная программа
echo форматирует и проверяет
echo новые диски
echo.
Если требуется отключить режим отображения команд и при этом не выводить на экран строку самой команды echo, введите символ @ перед командой:
@echo off
Оператор if и команду echo можно использовать в одной командной строке: Например:
if exist *.rpt echo Отчет получен.
При выводе русских букв необходимо помнить о кодировке. Текст сообщения должен быть в DOS (866) кодировке. Многие текстовые редакторы его поддерживают.
Если необходимо, что бы текст сообщений был в WIN (1251) кодировке и был виден из любого редактора, то можно использовать следующий прием.
chcp 1251 >NUL
set x=Русский текст
chcp 866 >NUL
echo %x%
pause
Такие сообщения для удобства можно выделить в отдельный блок.
chcp 1251 >NUL
set MSG01=Отсутствует исходный файл
set MSG02=Ошибка копирования
set MSG03=Успешное завершение программы
set TIT=Копирование файла
chcp 866 >NUL
Title %TIT%
….
echo %MSG01%
….
echo %MSG02%
….
echo %MSG03%
Если такой блок неудобно располагать в начале файла, то можно образовать из него процедуру, разместить в конце bat файла, а на исполнение вызвать эту процедуру командой call в начале bat файла. Из примера все должно стать понятнее))
….
call :blockmsg
Title %TIT%
….
echo %MSG01%
….
echo %MSG02%
….
echo %MSG03%
….
exit
:blockmsg
chcp 1251 >NUL
set MSG01=Отсутствует исходный файл
set MSG02=Ошибка копирования
set MSG03=Успешное завершение программы
set TIT=Копирование файла
chcp 866 >NUL
exit /b
Если сообщение одиночное, то можно извратиться поступить следующим образом:
chcp 1251 >nul
for /f «delims=» %%A in («Отойдите на безопасное расстояние») do >nul chcp 866& echo.%%A

Every scripting and programming language contains an error handler like Java contains try-catch
for error handling. In a Batch script, there is no direct way to do this, but we can create an error handler in the Batch script using a built-in variable of the Batch script name %ERRORLEVEL%
.
This article will show how we can create a Batch script to handle errors and failures. Also, we are going to some examples that make the topic easier.
Error Handling in Batch Script
When a command successfully executes, it always returns an EXIT CODE
that indicates whether the command successfully executed or failed to execute. So, to create an error handling in a Batch file, we can use that EXIT CODE
in our program.
You can follow below general format to create an error handler:
@Echo off
SomeCommand && (
ECHO Message for Success
) || (
ECHO Message for Failure or Error
)
We can also do that by checking the variable named %ERRORLEVEL%
. If the variable contains a value not equal to 0
, then there might be a problem or error when executing the command. To test the %ERRORLEVEL%
variable, you can follow the below example codes:
@ECHO off
Some Command Here !!!
IF %ERRORLEVEL% NEQ 0 (Echo Error found when running the command &Exit /b 1)
You must note that the keyword NEQ
means Not Equal. And the variable %ERRORLEVEL%
will only contain a non-zero value if there is a problem or error in the code.
An Example That Contains Errors
Below, we shared an example. We will run a Batch file named Your_file.bat
from a location.
We intentionally removed that file from the directory. So it’s an error command.
The code for our example will be:
@echo off
ECHO Running a Batch file
CD G:BATCH
CALL Your_file.bat
IF errorlevel 1 GOTO ERROR
ECHO The file run successfully.
GOTO EOF
:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1
:EOF
Now, as the file doesn’t exist in the directory, it will show an error, and you will get the below output when you run the code shared above.
Output:
Running a Batch file
The system cannot find the path specified.
'Your_file.bat' is not recognized as an internal or external command,
operable program or batch file.
The file didn't run successfully.
An Error-Free Code Example That Runs Successfully
In the example above, we made a mistake on the code intentionally to understand how the code works. If we correct it like below:
@echo off
ECHO Running a Batch file
CALL "G:BATCHYourfile.bat"
IF errorlevel 1 GOTO ERROR
ECHO The file runs successfully.
GOTO EOF
:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1
:EOF
Then we will get an output like this:
Running a Batch file
This is from the first file
The file runs successfully.
Remember, all commands we discussed here are only for the Windows Command Prompt or CMD environment.