Issue
The following command outputs some error (e.g. "The specified path was not found" ...). How can I prevent this command from displaying anything ?
@echo off
cd C:\test
for /d %%a in (*) do (
echo [test]>"%%a\test.txt"
echo %%a >>"%%a\test.txt"
)
Any help is welcome.
Thanks
Solution
@echo off
cd C:\test 2>nul || exit /b 1
for /d %%a in (*) do (
echo [test]>"%%a\test.txt"
>>"%%a\test.txt" echo %%a
)
If C:\test
does not exist, then cd
will message the error to stderr of path not found. You can silence the error message by redirecting stderr to nul with 2>nul
. 2
is the stderr stream.
Since cd
is important for the following code in the script, then use of ||
which is if previous command fails, do the command following that command with exit /b 1
.
Also, to avoid trailing space with echo to file, you can place the redirect before the echo command instead of after e.g. >>"%%a\test.txt" echo %%a
.
Or e.g. from comment:
@echo off
set "Source=C:\test"
set "Target=D:\data"
cd "%Source%" 2>nul || exit /b 1
if not exist "%Target%" exit /b 2
for /d %%a in (*) do (
> "%Target%\%%a\test.txt" echo [test]
>> "%Target%\%%a\test.txt" echo %%a
)
pause
exit
Source is handled by error condition of cd
and Target is handled by if not exist
. So if Target does not exist, exit /b 2
, as it is unsuitable to continue the script. So you can check errorlevel
1 or 2 for failure of the script if run i.e. from a command prompt.
Here is a alternative that proceeds to the end of the script:
@echo off
set "Source=C:\test"
set "Target=D:\data"
cd "%Source%" 2>nul && (
if exist "%Target%" (
for /d %%a in (*) do (
> "%Target%\%%a\test.txt" echo [test]
>> "%Target%\%%a\test.txt" echo %%a
)
)
)
pause
exit
Note I changed ||
to &&
to now condition on success instead of failure.
Goto can help to progress to avoid the parentheses blocks:
@echo off
set "Source=C:\test"
set "Target=D:\data"
cd "%Source%" 2>nul || goto :step2
if not exist "%Target%" goto :step2
for /d %%a in (*) do (
> "%Target%\%%a\test.txt" echo [test]
>> "%Target%\%%a\test.txt" echo %%a
)
:step2
rem other code
pause
exit
Answered By - michael_heath Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.