1

I have some code running, I wanne make it nicer though.

Currently my code is:

@echo off
echo Starting Program 1 ... >> %log%
call Program1.cmd
if %ERRORLEVEL%==1 (
    echo Error. >> %log%
) else (
    echo Success. >> %log%
)

I would like to keep the two echos within the code because I find it better for debug reasons. However, I do not like two output lines for it. How do I need to change the code to get this output:

Starting Program 1 ... Success

Thank you for your help, Peter

Peter Frey
  • 361
  • 4
  • 17

2 Answers2

1

You can misuse the set /p command to output a line without line feed.

@echo off
<nul set /p "=Starting Program 1 ..." >> %log%
call Program1.cmd
if %ERRORLEVEL%==1 (
    echo Error. >> %log%
) else (
    echo Success. >> %log%
)
jeb
  • 78,592
  • 17
  • 171
  • 225
0

You have to store the first message into a variable and then use it in the last redirection to file.

To use your code it would look like this:

@echo off
set "log=C:\t\so\batch\log.log"
set "message=Starting Program 1 ... "
call Program1.cmd
if %ERRORLEVEL%==1 (
    echo %message% Error. >> %log%
) else (
    echo %message% Success. >> %log%
)

Edit In my script above you may lose the logging information if something goes seriously wrong with the called script.

You could do it like this:

@echo off
set "log=C:\t\so\batch\log.log"
echo | set /p message="Starting Program 1 ... " >> %log%
call Program1.cmd
if %ERRORLEVEL%==1 (
    echo Error. >> %log%
) else (
    echo Success. >> %log%
)

The /p switch:

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Note: here the message is just a dummy variable.

There is a complex answer from dbehham on this topic.

tukan
  • 17,050
  • 1
  • 20
  • 48
  • do I risk losing "Starting Program 1 ..." in log if there is an error during call program1.cmd ? Can one just remove the last linebreak within the log file? – Peter Frey Jan 14 '20 at 07:52
  • @PeterFrey Yes you do lose that information if you directly the call script hangs or such unexptected issue occurs, otherwise, you should get the result based on the `%ERRORLEVEL%`. Removing the line break is unncessarly complex. I'll post some ways how to do it. – tukan Jan 14 '20 at 07:57