Чтобы bat не выводил ошибку

Razvedka2020

40 / 35 / 9

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

Сообщений: 201

1

Как скрыть ошибку выполнения?

22.02.2020, 22:15. Показов 13289. Ответов 8

Метки нет (Все метки)


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

Здравствуйте уважаемые форумчане. Решил навести красоту в своих скриптах и столкнулся с неприятностями, а именно с отображением ошибок (код импровизированный):

Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
SET HKLM_WINSENT="HKLMSoftwareWinsent SoftwareWinSent MessengerOptions"
 
::REG QUERY %HKLM_WINSENT% > NUL
REG QUERY %HKLM_WINSENT% || ECHO Идем дальше...
 
IF %ERRORLEVEL% EQU 1 (
::ECHO Код ошибки: %ERRORLEVEL%
GOTO Step2
) ELSE (
ECHO Какие-то команды - 6 (new_file)
ECHO Какие-то команды - 7 (new_file)
)
 
: Step2
PAUSE

Как скрыть ошибку выполнения?

Вопрос: как можно избавится от отображения ошибок?
Всем заранее большое человеческое спасибо.



0



alpap

4332 / 2122 / 661

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

Сообщений: 6,823

23.02.2020, 03:54

2

Windows Batch file
1
2
3
3 ...
4 2>nul ...
5 ...



1



Razvedka2020

40 / 35 / 9

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

Сообщений: 201

23.02.2020, 05:45

 [ТС]

3

Я может быть не понимаю ваш ответ, но в строке 3 я уже пробовал конструкцию (она не помогла и я ее закоментировал)

Bash
1
REG QUERY %HKLM_WINSENT% > NUL

Это не помогает избавится от вывода ошибки, так же как и

Bash
1
REG QUERY %HKLM_WINSENT% || ECHO Идем дальше...

Результат одинаков, на скриншоте.



0



6578 / 1778 / 304

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

Сообщений: 6,273

23.02.2020, 07:11

4

Цитата
Сообщение от Razvedka2020
Посмотреть сообщение

Решил навести красоту в своих скриптах

И тут же воткнёшься носом в неразрешимое противоречие понятия красоты.



0



5851 / 2563 / 1007

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

Сообщений: 8,750

23.02.2020, 07:16

5

Цитата
Сообщение от Razvedka2020
Посмотреть сообщение

но в строке 3 я уже пробовал конструкцию

А где там 2>nul спереди?



0



Razvedka2020

40 / 35 / 9

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

Сообщений: 201

23.02.2020, 07:20

 [ТС]

6

Цитата
Сообщение от FlasherX
Посмотреть сообщение

А где там 2>nul спереди?

Можно для особо «одаренных» пояснить что за

Bash
1
2>nul

или где про это почитать?



0



6578 / 1778 / 304

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

Сообщений: 6,273

23.02.2020, 07:47

7

Лучший ответ Сообщение было отмечено Razvedka2020 как решение

Решение

Программная абстракция существования стандартных файловых потоков в виде их описателей (handles)
STDIN, STDOUT и STDERR
исторически поддерживается в командных оболочках с помощью чисел соответственно
0, 1 и 2
и загадочных значков
> < &

Код

ECHO "раз два три-пять зайтчик погулять"  1 > NUL   2 > &1

интерпретатор распознает сочетание 1 > NUL ( {одинокая цифра}
как инструкцию направить стандартный поток вывода (цифра 1 — это STDOUT) в устройство NUL,
а также направить стандартный поток ошибок ( цифра 2 — это STDERR ) в стандартный поток вывода,
который в нашем случае назначен уже для вывода в NUL. Чтобы отличать реальное имя файла от абстрактного описателя перед последним ставят значок &.



1



5851 / 2563 / 1007

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

Сообщений: 8,750

23.02.2020, 08:11

8

Лучший ответ Сообщение было отмечено Razvedka2020 как решение

Решение



1



40 / 35 / 9

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

Сообщений: 201

23.02.2020, 08:14

 [ТС]

9

Большое вам всем человеческое спасибо. Не зря говорят: Век живи, век учись…



0



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

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.

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.

Доброе время суток, подскажите столкнулся со следующей проблемой.
У меня есть 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

но это не помогло, код все равно останавливается и не работает дальше.

Собственно как его заставить игнорировать коды ответа и продолжать работать во что бы то не было?

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