Coloring Two Different Texts in a BAT File

Abstract: Display two different texts in distinct colors within a single batch file using the color command and hex codes.

Created: 2026-08-28 by
To display two different texts in distinct colors within a single batch file, you must use the 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-in color 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 the color 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:
  1. Set the initial color for the first text block.
  2. Echo the first text.
  3. Set the new color for the second text block.
  4. Echo the second text.
  5. (Optional) Reset the color to the default or a neutral state.
Here is a practical example demonstrating this sequence:
@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 executing color /? 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 CMD color 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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More