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
2 / 2 / 0 Регистрация: 22.04.2013 Сообщений: 24 |
|
1 |
|
08.10.2013, 15:40. Показов 13223. Ответов 10
Всем привет!
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 — не работает
0 |
Модератор 4927 / 1982 / 386 Регистрация: 06.01.2013 Сообщений: 4,674 |
|
08.10.2013, 16:12 |
4 |
Можете сбросить сюда весь код бат-файла (теги для выделения используем [bash]) ?
0 |
scobit 2 / 2 / 0 Регистрация: 22.04.2013 Сообщений: 24 |
||||
08.10.2013, 16:43 [ТС] |
5 |
|||
Добавлено через 13 минут Добавлено через 14 минут
0 |
Dragokas 18041 / 7644 / 891 Регистрация: 25.12.2011 Сообщений: 11,426 Записей в блоге: 17 |
||||||||
08.10.2013, 16:44 |
6 |
|||||||
Синтаксис неверный. Так:
или так:
Можно вопрос? — А что такое Вискас
0 |
2 / 2 / 0 Регистрация: 22.04.2013 Сообщений: 24 |
|
08.10.2013, 16:47 [ТС] |
7 |
Синтаксис верный. Если не брать в расчет ошибку (по теме) то всё работает на ура.
0 |
18041 / 7644 / 891 Регистрация: 25.12.2011 Сообщений: 11,426 Записей в блоге: 17 |
|
08.10.2013, 16:52 |
8 |
Это судя из файла помощи верный, а на самом деле нет.
0 |
2 / 2 / 0 Регистрация: 22.04.2013 Сообщений: 24 |
|
08.10.2013, 16:55 [ТС] |
9 |
Ну так я файл проверял же, запускал — всё ок.
0 |
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 |
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 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
.