color command to change the console's foreground and background attributes before each echo statement. The color command accepts a two-character hex code where the first character defines the background color and the second defines the text color. By saving the current color settings at the start of the script using set /a oldColor=%1, or by relying on the default state, you can reset the palette after printing colored output to ensure subsequent lines remain readable. This approach allows for clear visual separation of status messages, errors, or informational text directly in the command prompt interface.
Understanding the Color Command Syntax
The foundation of coloring text in Windows Batch files is the built-incolor command. Unlike many programming languages that require external libraries or complex escape sequences, Windows CMD provides this functionality natively. The syntax is straightforward: color [attr], where attr specifies the color attributes for console appearance.
The attribute value consists of two hexadecimal digits. The first digit corresponds to the background color, while the second digit represents the text (foreground) color. If either digit is omitted, the command retains the previous setting for that specific aspect. For example, running color 0A sets the background to black (0) and the text to bright green (A). It is crucial to understand that this command changes the global state of the current console session until it is changed again. Therefore, if you print a red error message, all subsequent text will also be red unless you explicitly reset the color.
Here is a quick reference for the hexadecimal codes used in the color command:
- 0: Black
- 1: Blue
- 2: Green
- 3: Aqua
- 4: Red
- 5: Purple
- 6: Yellow
- 7: White
- 8: Gray
- 9: Light Blue
- A: Light Green
- B: Light Aqua
- C: Light Red
- D: Light Purple
- E: Light Yellow
- F: Bright White
Implementing Multiple Colors in Sequence
To achieve the goal of displaying two different texts in different colors, you need to structure your batch file to set the color, print the text, and then potentially reset the color for the next section. A common pattern involves defining variables for your desired colors to make the script more maintainable. However, since thecolor command does not support variable expansion directly in its argument in older versions of Windows, it is often safer to hardcode the hex values or use delayed expansion if necessary.
Consider the following logical flow for a script that prints a header in one color and a body in another:
- Set the initial color for the first text block.
- Echo the first text.
- Set the new color for the second text block.
- Echo the second text.
- (Optional) Reset the color to the default or a neutral state.
@echo off
:: Set background to black, text to cyan for the header
color 0C
echo ========================================
echo SYSTEM STATUS REPORT
echo ========================================
:: Reset color to white on black for the main content
color 07
echo.
echo Processing started at %date% %time%.
echo Checking system resources...
echo All systems operational.
echo.
:: Change to yellow text for warnings
color 0E
echo Warning: Disk space is below 10%.
echo Please check drive C:.
pause
In this example, the header appears in light red (C) on a black background. Immediately after, the color is switched to white (7) on black (0) for the standard information. Finally, a warning is displayed in bright yellow (E) on black. This visual hierarchy helps users quickly identify critical information without reading every line carefully.
Preserving Original Console Settings
One significant risk when modifying console colors is leaving the terminal in an unreadable state after the script finishes. If your script ends with a bright pink background and light gray text, the user might struggle to type further commands. To mitigate this, you should always restore the original console colors at the end of your batch file. You can retrieve the current color settings before making any changes by executingcolor /? which displays help, but more effectively, you can capture the current attribute using environment variables. Although direct capture via for /f "tokens=2 delims==" %%G in ('color') do ... is unreliable because color does not output its current state to stdout easily, a robust method is to store the default color at the very beginning of the script.
Most Windows consoles default to 07 (Black background, White text). You can assume this as a safe fallback. Add the following line at the very top of your script:
set DEFAULT_COLOR=07
Then, add this line at the very bottom, just before exit or pause:
color %DEFAULT_COLOR%
This ensures that regardless of how many color changes occurred during execution, the user returns to a standard, high-contrast view. This practice is essential for scripts that are part of larger automated workflows or are run frequently by system administrators.
Troubleshooting Common Issues
When implementing colored text in batch files, several issues may arise. First, ensure that you are running the script in a standard Command Prompt window. Some third-party terminal emulators or PowerShell consoles may interpret ANSI escape codes differently than the legacy CMDcolor command, though the color command itself is universally supported in cmd.exe.
Another common mistake is forgetting to separate the background and foreground codes. Remember that the first digit is background. If you want white text on a blue background, you use 17 (Blue background, White text), not 71. Reversing these digits will result in black text on a white background, which is often harder to read.
Additionally, be aware that the color command affects the entire window, not just the current line. There is no native way to have multiple colors on the same line of text using only the color command. If you need mixed colors on a single line, you would need to use alternative methods such as calling PowerShell or using VBScript, which are beyond the scope of basic batch file coloring. For most use cases, however, switching colors between lines provides sufficient clarity.
For more advanced batch scripting challenges, such as handling spaces in file paths which can interfere with color-coded output redirection, consider reviewing related guides on managing file names in scripts.
Batch File Not Working with Space in File Name is particularly relevant if your colored output is being redirected to a file rather than displayed on screen, as special characters can sometimes cause parsing errors that disrupt the color logic.
Frequently Asked Questions
Can I use more than two colors in a single batch file?
Yes, you can use as many colors as needed by calling the color command multiple times throughout the script. Each call updates the active color scheme for all subsequent text until it is changed again. Just remember to reset the color at the end to avoid leaving the console in an awkward state.
Why does my text disappear when I change colors?
This usually happens if you accidentally set both the background and foreground colors to the same value, such as color 00 (black on black). Always ensure that the two hexadecimal digits represent contrasting colors so that the text remains visible against the background.
Is it possible to have different colors on the same line?
No, the native color command in Windows Batch files applies to the entire console window, not individual characters or lines. To achieve multi-colored text on a single line, you must use external tools like PowerShell commands embedded within the batch file or third-party utilities.
How do I find out what color code corresponds to a specific color?
You can refer to the hexadecimal table provided in the "Understanding the Color Command Syntax" section above. Alternatively, you can test codes interactively by opening a command prompt and typing color followed by various two-digit combinations to see their effects immediately.
Does the color command work in PowerShell?
The color command is specific to cmd.exe. In PowerShell, you should use the Write-Host cmdlet with the -ForegroundColor and -BackgroundColor parameters. While PowerShell can call the color command, it is not the recommended approach for styling text within PowerShell scripts.