批处理脚本:链接命令时出现彩色回声的问题 [英] Batch script : issue with colored echo when chaining commands
问题描述
在尝试使用批处理脚本以彩色显示某些文本时,我目前遇到问题.
I am currently facing an issue when trying to echo some text in color with a batch script.
仅当我尝试根据下一个命令的状态码在另一个命令(此处为git命令)后回显颜色时,才会发生我的问题:&&或||.
My issue only happens when I try to echo in color after another command (git command here) depending on the status code of the previous command : with && or ||.
示例:
@echo off
cls
for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
echo %ESC%[92mGreen%ESC%[0m
echo %ESC%[91mRed%ESC%[0m
echo %ESC%[92mGreen%ESC%[0m && echo %ESC%[91mRed%ESC%[0m
git pull || echo %ESC%[92mGreen%ESC%[0m && echo %ESC%[91mRed%ESC%[0m
pause
如您所见,在执行git pull命令后,彩色回显不再起作用.如果我使用&&代替||如果git pull返回成功.
As you can see, echo in color doesn't work anymore after my git pull command. This will be the same if I use && instead of || and if git pull returns success.
有什么主意吗?
谢谢.
推荐答案
只需调用标签,并在标签内引用颜色:
Just call labels and have the colors referenced inside the labels:
@echo off
cls
for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
call :green
call :red
git pull && call :green || call :red
goto :eof
:green
echo %ESC%[92mSuccess%ESC%[0m
goto :eof
:red
echo %ESC%[91mFailed%ESC%[0m
goto :eof
结果:
请注意条件运算符的顺序为:
Note the sequence of the conditional operators are:
command && errorlevel is 0 || errorlevel is larger than 0
换句话说,命令and
如果成功,or
如果不成功
in other words, command and
if successful or
if not successful
这篇关于批处理脚本:链接命令时出现彩色回声的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!