Search code examples
batch-fileecho

Batch Echo Style: two statements into same line


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


Solution

  • 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.