Bat игнорировать ошибки

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.

a_horse_with_no_name's user avatar

asked Nov 30, 2013 at 9:35

charqus's user avatar

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 Rowland's user avatar

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

user1976's user avatar

user1976user1976

3534 silver badges15 bronze badges

2 / 2 / 0

Регистрация: 22.04.2013

Сообщений: 24

1

08.10.2013, 15:40. Показов 13223. Ответов 10


Студворк — интернет-сервис помощи студентам

Всем привет!
К примеру мне необходимо запустить файл
start /D «C:Program Files (x86)Microsoft OfficeOffice14» OUTLOOK.EXE
Но по каким то причинам это не получается и выходит ошибка «Не удается найти … Проверьте правильно ли указано имя и так далее».
Проблема не в том, что выходит это сообщение, а в том, что bat файл прекращает свое выполнение до тех пор пока не нажмешь «ok». Как это исправить?
Как сделать так, чтобы ошибка не выходила или игнорировалась?



0



Модератор

4927 / 1982 / 386

Регистрация: 06.01.2013

Сообщений: 4,674

08.10.2013, 16:04

2

После этой крманды добавь еще pause>nul



0



2 / 2 / 0

Регистрация: 22.04.2013

Сообщений: 24

08.10.2013, 16:08

 [ТС]

3

pause>nul — не работает
+ после моей команды выполняется if errorlevel
и в итоге ничего не получается



0



Модератор

4927 / 1982 / 386

Регистрация: 06.01.2013

Сообщений: 4,674

08.10.2013, 16:12

4

Можете сбросить сюда весь код бат-файла (теги для выделения используем [bash]) ?
Просто батник не должен после ошибки одной из команд прекращаться — исключение в ошибке в синтаксисе if goto call for



0



scobit

2 / 2 / 0

Регистрация: 22.04.2013

Сообщений: 24

08.10.2013, 16:43

 [ТС]

5

Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
cls
@echo off
title Check Outlook.exe process
echo Search...
echo Don't close the window (5-30 seconds)
TaskList|>Nul FindStr /BI "outlook.exe"
pause>nul
if errorlevel 1 goto NoRecord
goto Done2
:NoRecord
start/D "C:Program Files (x86)Microsoft OfficeOffice14" OUTLOOK.EXE
ping -n 20 127.0.0.1 >NUL
TaskList|>Nul FindStr /BI "outlook.exe"
if errorlevel 1 goto NoRecord2
goto Done2
:NoRecord2
start /D "D:viskascheck" ViskasMailReport.vbs
:Done2
ping -n 3 127.0.0.1 >NUL
exit

Добавлено через 13 минут
К примеру если в этой строчке
start/D «C:Program Files (x86)Microsoft OfficeOffice14» OUTLOOK.EXE
не правильно написать Outlook.exe — выйдет ошибка и bat файл не продолжает работу.

Добавлено через 14 минут
pause>nul — это я добавил уже по Вашей рекомендации. В исходном варианте этого не было.



0



Dragokas

Эксперт WindowsАвтор FAQ

18041 / 7644 / 891

Регистрация: 25.12.2011

Сообщений: 11,426

Записей в блоге: 17

08.10.2013, 16:44

6

Синтаксис неверный.

Так:

Bash
1
start "" "C:Program Files (x86)Microsoft OfficeOffice14OUTLOOK.EXE"

или так:

Bash
1
start "" /D "C:Program Files (x86)Microsoft OfficeOffice14" OUTLOOK.EXE

Можно вопрос? — А что такое Вискас



0



2 / 2 / 0

Регистрация: 22.04.2013

Сообщений: 24

08.10.2013, 16:47

 [ТС]

7

Синтаксис верный. Если не брать в расчет ошибку (по теме) то всё работает на ура.
viskas — название почтового ящика.
Нужно как то игнорировать это сообщение.



0



Эксперт WindowsАвтор FAQ

18041 / 7644 / 891

Регистрация: 25.12.2011

Сообщений: 11,426

Записей в блоге: 17

08.10.2013, 16:52

8

Это судя из файла помощи верный, а на самом деле нет.
Путь может быть распознать как Title, в результате файл не запуститься.
Безопаснее ВСЕГДА указывать пустой Title.



0



2 / 2 / 0

Регистрация: 22.04.2013

Сообщений: 24

08.10.2013, 16:55

 [ТС]

9

Ну так я файл проверял же, запускал — всё ок.
Все работает как нужно.
Или Вы хотите сказать, что если я сделаю по Вашему совету, то ошибка не будет выходить?



0



Эксперт WindowsАвтор FAQ

18041 / 7644 / 891

Регистрация: 25.12.2011

Сообщений: 11,426

Записей в блоге: 17

08.10.2013, 17:03

10

Именно.

Добавлено через 1 минуту
А файл-то на самом деле существует?



0



2 / 2 / 0

Регистрация: 22.04.2013

Сообщений: 24

08.10.2013, 17:12

 [ТС]

11

да, всё есть. Всё работает.



0



Error Handling in Batch Script

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.

Доброе время суток, подскажите столкнулся со следующей проблемой.
У меня есть bat скрипт который накатывает обновления на сайте

@echo off
set /p is_migrate=Use migration?(Y/N):
@echo on
cd C:inetpubwwwroot
git  -c http.sslVerify=false fetch origin master
git merge origin/master
npm install
npm run build
composer update
composer dump-autoload --optimize
IF "%is_migrate%"=="Y" (
"C:Program FilesPHPv7.4php.exe" -f C:inetpubwwwrootbinconsole doctrine:migrations:diff & 
"C:Program FilesPHPv7.4php.exe" -f C:inetpubwwwrootbinconsole doctrine:migrations:migrate --no-interaction
)

"C:Program FilesPHPv7.4php.exe" -f C:inetpubwwwrootbinconsole cache:clear
"C:Program FilesPHPv7.4php.exe" -f C:inetpubwwwrootbinconsole cache:warmup
pause

Но после отработки команды npm install он падает хотя команда отрабатывает нормально, немного поковырявшись я его поменял на

@echo off
set /p is_migrate=Use migration?(Y/N):
@echo on
cd C:inetpubwwwroot
git  -c http.sslVerify=false fetch origin master
git merge origin/master
npm install & npm run build & composer update & composer dump-autoload --optimize

IF "%is_migrate%"=="Y" (
"C:Program FilesPHPv7.4php.exe" -f C:inetpubwwwrootbinconsole doctrine:migrations:diff & 
"C:Program FilesPHPv7.4php.exe" -f C:inetpubwwwrootbinconsole doctrine:migrations:migrate --no-interaction
)

"C:Program FilesPHPv7.4php.exe" -f C:inetpubwwwrootbinconsole cache:clear
"C:Program FilesPHPv7.4php.exe" -f C:inetpubwwwrootbinconsole cache:warmup
pause

После чего он стал отрабатывать до команды

composer dump-autoload --optimize и останавливаться, что подтвердило что скорее всего команда при успешной работе возвращает не тот код который ожидает cmd.exe и считает что программа завершилась ошибкой хотя это не так.

Я попробовал сделать так

npm install & npm run build & composer update & composer dump-autoload --optimize & set ERRORLEVEL=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 command echo| set /p="..." ends: 0 if writing the file succeeded, 1 if it failed. On the contrary, using a nameless command echo| 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.

Понравилась статья? Поделить с друзьями:
  • Bash убрать вывод ошибок
  • Bash синтаксическая ошибка ожидается операнд неверный маркер
  • Bash подавление вывода ошибок
  • Bash подавить вывод ошибок
  • Bash ошибка синтаксиса неожиданный конец файла