[HowTo] Incorporar colores, estilos y efectos en scripts de bash
Las ‘secuencias de escape’ son una especie de códigos que indican al sistema que allí donde se encuentra la secuencia de escape hay, por ejemplo, un salto de línea, o una negrita.
En bash se puede emplear unos códigos que sirven para que, en la ejecución del script, el texto se muestre de una determinada forma, con estilos, colores y efectos.
Esos códigos o secuencias de escape son:
- Sin formato / anular formato
\033[00m
ô\x1b[2m
p.ej…echo -e '\x1b[2mnormal'
… anularía todos los efectos anteriormente aplicados, con lo que la palabra ‘normal’ se mostraría por pantalla sin ningún tipo de formato especial.
- Rojo
ô
p.ej. ~~~
<br>
* Verde
`` ô ``
p.ej.
<br>
* Amarillo
`` ô ``
p.ej.
<br>
* Púrpura
`` ô ``
p.ej.
<br>
* Cyan
`` ô ``
p.ej.
~~~
NONE=’\033[00m’ RED=’\033[01;31m’ GREEN=’\033[01;32m’ YELLOW=’\033[01;33m’ PURPLE=’\033[01;35m’ CYAN=’\033[01;36m’ WHITE=’\033[01;37m’ BOLD=’\033[1m’ UNDERLINE=’\033[4m’
echo -e “\x1b[1m bold” echo -e “\x1b[30m black” echo -e “\x1b[31m red” echo -e “\x1b[32m green” echo -e “\x1b[33m yellow” echo -e “\x1b[34m blue” echo -e “\x1b[35m mag” echo -e “\x1b[36m cyan” echo -e “\x1b[37m white”
echo -e “\x1b[0m io-std” echo -e “\x1b[1m bold” echo -e “\x1b[2m normal”
echo -e “\x1b[3m italic” echo -e “\x1b[4m underlined” echo -e “\x1b[5m blinking” echo -e “\x1b[7m inverted”
Modo de empleo
echo -e “This text is ${RED}red${NONE} and ${GREEN}green${NONE} and ${BOLD}bold${NONE} and ${UNDERLINE}underlined${NONE}.”
#Unix & Linux Stack Exchange Feed for question ‘Change font in echo command’
Stack Exchange Network
Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. Visit Stack Exchange (BUTTON) ________ Loading… 1. 2. 0 3. +0 4. + Tour Start here for a quick overview of the site + Help Center Detailed answers to any questions you might have + Meta Discuss the workings and policies of this site + About Us Learn more about Stack Overflow the company + Business Learn more about hiring developers or posting ads with us 5. 6. Log in Sign up 7.
current community + Unix & Linux help chat + Unix & Linux Meta
your communities Sign up or log in to customize your list.
more stack exchange communities company blog
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up. Sign up to join this community [anonymousHeroQuestions.svg?v=748bfb046b78] Anybody can ask a question [anonymousHeroAnswers.svg?v=d5348b00eddc] Anybody can answer [anonymousHeroUpvote.svg?v=af2bb70d5d1b] The best answers are voted up and rise to the top (BUTTON)
Unix & Linux Sponsored by Sponsored logo [B25058705.294197466;dc_trk_aid=487473321;dc_trk_cid=142595284;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755}?]
1. Home
2.
1. Questions
2. Tags
3. Users
4. Unanswered
5. Jobs
Change font in echo command
Ask Question Asked 8 years, 10 months ago Active 18 days ago Viewed 94k times (BUTTON) 20 (BUTTON) (BUTTON) 12
Is it possible to change the font attributes of the output of echo in either zsh or bash?
What I would like is something akin to: echo -n “This is the font: normal “ echo -n $font=italic “italic,” echo -n $font=bold “bold,” echo -n “and” echo -n $font=small “small”.
so that it print: “This is the font: normal, italic, bold, [^small]” within a line of text. bash shell zsh fonts Share Improve this question (BUTTON) Follow edited May 26 ‘15 at 12:24 Sardathrion - against SE abuse asked Apr 25 ‘12 at 8:15 Sardathrion - against SE abuseSardathrion - against SE abuse 4,18155 gold badges2626 silver badges6060 bronze badges 2 * This has more to do with the terminal emulator in question than with the used shell. This question thread contains some valuable pointers, I think – sr_ Apr 25 ‘12 at 8:33 * Normally, you cannot change the font size. The only thing, you usually can do, is changing color and sometimes the bold/underlined attribute. For this, you can use ANSI escape sequences. See e.g. bashguru.com/2010/01/shell-colors-colorizing-shell-scripts.html for some examples. – jofel Apr 25 ‘12 at 8:35
Add a comment |
4 Answers 4
Active Oldest Votes (BUTTON) 20 (BUTTON)
On most if not all terminal emulators, you can’t set different font sizes or different fonts, only colors and a few attributes (bold, underlined, standout).
In bash (or in zsh or any other shell), you can use the terminal escape sequences directly (apart from a few exotic ones, all terminals follow xterm’s lead these days). CSI is ESC [, written $’\e[’ in bash. The escape sequence to change attributes is CSI Ps m. echo $’\e[32;1mbold red\e[0mplain\e[4munderlined’
Zsh has a convenient function for that. autoload -U colors colors echo $bold_color$fg[red]bold red${reset_color}plain$’\e’$color[underline]munderlined
Or can do it as part of prompt expansion, also done with print -P, or the % parameter expansion flag: print -P ‘%F{red}%Bbold%b red%f %Uunderline%u’
Share Improve this answer (BUTTON) Follow edited Jun 21 ‘20 at 17:29 Stéphane Chazelas 411k7272 gold badges808808 silver badges12221222 bronze badges answered Apr 27 ‘12 at 0:33 Gilles ‘SO- stop being evil’Gilles ‘SO- stop being evil’ 677k166166 gold badges14161416 silver badges19151915 bronze badges
Add a comment | (BUTTON) 19 (BUTTON)
You could include these color definitions in a script or source file. Could look something like this. #!/bin/bash PATH=/bin:/usr/bin:
NONE=’\033[00m’ RED=’\033[01;31m’ GREEN=’\033[01;32m’ YELLOW=’\033[01;33m’ PURPLE=’\033[01;35m’ CYAN=’\033[01;36m’ WHITE=’\033[01;37m’ BOLD=’\033[1m’ UNDERLINE=’\033[4m’
echo -e “This text is ${RED}red${NONE} and ${GREEN}green${NONE} and ${BOLD}bold${NONE} and ${UNDERLINE}underlined${NONE}.”
tput sgr0
Notice that you should reset the ANSI color codes after each instance you invoke a change. The tput sgr0 resets all changes you have made in the terminal.
I believe changing the font size or italics would be specific to the terminal you are using.
While this guide is specific to customizing your bash prompt, it is a good reference for color codes and generates some ideas of what you can do. Share Improve this answer (BUTTON) Follow edited Apr 25 ‘12 at 12:23 answered Apr 25 ‘12 at 12:17 George MGeorge M 11.6k33 gold badges3535 silver badges4949 bronze badges 0
Add a comment | (BUTTON) 6 (BUTTON)
Seems as if the layout can’t handle the [0x1b]-character in front of the [.
The first line makes bold: echo -e “\x1b[1m bold” echo -e “\x1b[30m black” echo -e “\x1b[31m red” echo -e “\x1b[32m green” echo -e “\x1b[33m yellow” echo -e “\x1b[34m blue” echo -e “\x1b[35m mag” echo -e “\x1b[36m cyan” echo -e “\x1b[37m white”
For the general type, I only know echo -e “\x1b[0m io-std” echo -e “\x1b[1m bold” echo -e “\x1b[2m normal”
and from the comments, thanks manatwork and GypsyCosmonaut: echo -e “\x1b[3m italic” echo -e “\x1b[4m underlined” echo -e “\x1b[5m blinking” echo -e “\x1b[7m inverted”
and don’t know the difference between io-std and normal.
I haven’t seen italic or small in the shell.
You can enter them (thanks to manatwork too) by Ctrl + v ESC in the Bash, where it will be displayed as ^[. This mean the whole ANSI sequence will look like ^[[1m bold or ^[[1mbold (to avoid the blank before ‘bold’).
Many editors have problems with (char)0x1b. Alternatives: copy/paste it from somewhere, or use echo -e “\x1b[1m bold”
in bash, or a hex editor.
Or, even simpler: echo -e “\e[1m bold”
The \e is an escape sequence for the ascii code 27, for the bash internal command echo as well as for the external program GNU-echo. Share Improve this answer (BUTTON) Follow edited Feb 17 at 12:47 answered Apr 25 ‘12 at 11:37 user unknownuser unknown 9,31922 gold badges2929 silver badges5454 bronze badges 4 * 1 Escape characters can be typed: Ctrl+V, Esc. (Will be displayed as “^[”. This mean the whole ANSI sequence will look like “^[[1mbold”.) – manatwork Apr 25 ‘12 at 11:49 * 1 There are more attributes to mention: \e[4m underlined, \e[5m blinking, \e[7m inverted. – manatwork Apr 25 ‘12 at 11:52 * @manatwork: added them. – user unknown Apr 25 ‘12 at 12:04 * @userunknown Thanks for helping, tinkering with your code, I found italic is echo -e “\x1b[3m italic” – GypsyCosmonaut Jul 16 ‘17 at 11:13
Add a comment | (BUTTON) 0 (BUTTON)
Here:
http://en.wikipedia.org/wiki/ANSI_escape_code
(note: a lot of them usually don’t work, but most of these are marked thus.)
I’m making a game in the terminal and have been relying heavily on the above link. It even tells you how to hide/unhide the cursor, make color (30’s), “bold” (lighter), darker, underlined, italic, background color (40’s instead of 30’s), etc. You can also change the cursor’s location (which is very helpful - for example, “\x1B[1A” moves the cursor up one line; “\x1B[0;0H” moves the cursor to row 0, col 0; “\x1B[2J” clears the screen; “\x1B[2K” clears the line.
For your purposes as people have said: echo -e “\x1b[30;44m black with blue background \x1b[m”
echo -e “\x1b[31;42m red with green background \x1b[m”
echo -e “\x1b[32;40m green with black background \x1b[m”
echo -e “\x1b[8m Invisible; na na na na boo boo \x1b[m”
Note: You need the -e in echo -e “\x1b[35;1m Light purple \x1b[m”
or you need to use single quotes. Type man echo to see why (double quotes are usually a pain when printing; when I need stuff to not expand or I need ANSI escape sequences, I use single quotes because it is easy - even though I gotten used to it from doing it so many times - to forget the -e in which case you get “box with numbers and letters[35;1m”).
Every time you see CSI replace it with “\x1b[” (or “\e[” or “\u1b[”). “\x1b[” I think is more standard, but I don’t really know what the difference is between them is. Share Improve this answer (BUTTON) Follow edited Jun 21 ‘16 at 8:09 Pierre.Vriens 1,1062121 gold badges1313 silver badges1616 bronze badges answered Oct 26 ‘14 at 20:21 DylanDylan 36533 silver badges1010 bronze badges 3 * If you like cluttering your strings with extra characters, don’t use \e :-) – clearlight Jan 15 ‘17 at 21:01 * @clearlight I am not sure what you mean. I think you might have meant to say “use \e”. However, \e is less supported than \x1b I have found. The optimal thing to do would be either esc=$’\e’ or esc=$’\x1b’ (this is in bash) and then use “${esc}[34;1m” (for, e.g., bright blue). I have a semi-complex example here (github.com/dylnmc/ps1porn/blob/master/powerline.sh) for a real bash prompt string ;) Please forgive the name of the repo – you can thank people in freenode’s channel #archlinux-offtopic for that. – Dylan Feb 3 ‘17 at 17:37 * Reason for doing esc=$’\e’ is that this allows bash to create the ansi-escape character on the spot, and you benefit from it in a couple of ways. Sometimes, in fact, (as is demonstrated in the github link), you have to use this method in order to get color to show up properly. For older versions of bash as well as the sh shell, you should (but don’t need to) use this method to get color to show up … granted that the terminal uses the escape sequences that most modern terminals do. – Dylan Feb 3 ‘17 at 18:05
Add a comment |
Your Answer
Thanks for contributing an answer to Unix & Linux Stack Exchange! * Please be sure to answer the question. Provide details and share your research!
But avoid … * Asking for help, clarification, or responding to other answers. * Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers. (BUTTON) Draft saved Draft discarded ________
Sign up or log in
Sign up using Google Sign up using Facebook Sign up using Email and Password (BUTTON) Submit
Post as a guest
Name ________ Email
Required, but never shown ______________
Post as a guest
Name ________ Email
Required, but never shown ______________ (BUTTON) Post Your Answer (BUTTON) Discard
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you’re looking for? Browse other questions tagged bash shell zsh fonts or ask your own question.
The Overflow Blog
* Podcast 318: What’s the half-life of your code?
* Best practices can slow your application down
Featured on Meta
* IBM will soon be sponsoring Unix & Linux!
Linked
15 Italics in Emacs on a text terminal (rxvt-unicode) 6 Xterm does not display one uni-code character
Related
40 Is there a unix command line tool that can analyze font files? 54 Can I change the font of the text-mode console? 6 Changing TTY font to a non-default font 20 How can I make commands appear bold in zsh? 6 How do I alias the bold weight of a font family to the bold weight of another font family? 0 How to remove bold font for file path in modified .bash_profile? 1 Change Shell Font via Command
Hot Network Questions
* Why can the effective number of bits be a non-integer? What does this physically represent?
* How to stop bike renters overextending seatposts?
* Which endian was the Intel 4004?
* Proofs of theorems that proved more or deeper results than what was first supposed or stated as the corresponding theorem
* Ball thrown faster than terminal velocity
* Pipetting: do human experimenters need liquid class information?
* Warning: DocumentRoot does not exist... But it does
* Slurs within slurs
* "Outside there is a money receiver which only accepts coins" - or "that only accepts coins"? Which relative pronoun is better?
* Where does -ι- come from in derivatives of ἅλς (ἁλιάετος, ἁλιαής, ἁλιανθής)?
* Can one still be a Muslim if he/she denies some verses that he/she found outdated or illogical?
* Can a Circle of the Stars Druid roll a natural d3 (or other odd-sided die) to bias their Cosmic Omen roll?
* What does the little-endian notation improve for Bitcoin?
* How much damage is dealt/taken when that damage also reduces a creature to 0 hit points?
* What is this nut called and can it be removed and reused/replaced?
* Has any European country recently scrapped a bank/public holiday?
* How to store the current value of a macro?
* LWE: Round a continuous Gaussian to a true Discrete Gaussian
* House of Commons clarification on clapping
* What's the ordering of 6 realms of rebirth?
* What would it take to make a PS/2 keyboard interface hot-swap?
* Does the Rubik's Cube in this painting have a solved state?
* Safety of taking a bicycle to a country where they drive on the other side of the road?
* Sleet Storm: do crampons stop you from falling prone?
more hot questions Question feed
Subscribe to RSS
Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader. https://unix.stackex lang-bsh
Unix & Linux
* Tour
* Help
* Chat
* Contact
* Feedback
* Mobile
Company
* Stack Overflow
* For Teams
* Advertise With Us
* Hire a Developer
* Developer Jobs
* About
* Press
* Legal
* Privacy Policy
* Terms of Service
Stack Exchange Network
* Technology
* Life / Arts
* Culture / Recreation
* Science
* Other
* Stack Overflow
* Server Fault
* Super User
* Web Applications
* Ask Ubuntu
* Webmasters
* Game Development
* TeX - LaTeX
* Software Engineering
* Unix & Linux
* Ask Different (Apple)
* WordPress Development
* Geographic Information Systems
* Electrical Engineering
* Android Enthusiasts
* Information Security
* Database Administrators
* Drupal Answers
* SharePoint
* User Experience
* Mathematica
* Salesforce
* ExpressionEngine® Answers
* Stack Overflow em Português
* Blender
* Network Engineering
* Cryptography
* Code Review
* Magento
* Software Recommendations
* Signal Processing
* Emacs
* Raspberry Pi
* Stack Overflow на русском
* Code Golf
* Stack Overflow en español
* Ethereum
* Data Science
* Arduino
* Bitcoin
* Software Quality Assurance & Testing
* Sound Design
* Windows Phone
* more (28)
* Photography
* Science Fiction & Fantasy
* Graphic Design
* Movies & TV
* Music: Practice & Theory
* Worldbuilding
* Video Production
* Seasoned Advice (cooking)
* Home Improvement
* Personal Finance & Money
* Academia
* Law
* Physical Fitness
* Gardening & Landscaping
* Parenting
* more (10)
* English Language & Usage
* Skeptics
* Mi Yodeya (Judaism)
* Travel
* Christianity
* English Language Learners
* Japanese Language
* Chinese Language
* French Language
* German Language
* Biblical Hermeneutics
* History
* Spanish Language
* Islam
* Русский язык
* Russian Language
* Arqade (gaming)
* Bicycles
* Role-playing Games
* Anime & Manga
* Puzzling
* Motor Vehicle Maintenance & Repair
* Board & Card Games
* Bricks
* Homebrewing
* Martial Arts
* The Great Outdoors
* Poker
* Chess
* Sports
* more (16)
* MathOverflow
* Mathematics
* Cross Validated (stats)
* Theoretical Computer Science
* Physics
* Chemistry
* Biology
* Computer Science
* Philosophy
* Linguistics
* Psychology & Neuroscience
* Computational Science
* more (10)
* Meta Stack Exchange
* Stack Apps
* API
* Data
* Blog
* Facebook
* Twitter
* LinkedIn
* Instagram
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.3.5.38726
Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group. This site is not affiliated with Linus Torvalds or The Open Group in any way.
Unix & Linux Stack Exchange works best with JavaScript enabled
— — —
Fuentes:
trac.transmissionbt.com
trac.transmissionbt.com - debian
--- --- ---
COMENTARIOS
Este blog no cuantifica ni monetiza al visitante. Sean muchos, sean pocos, no me importan esos detalles, de dónde vienen o a dónde van; lo que aquí se expone está escrito por puro placer. Este blog prefiere sacrificar un sistema de comentarios cómodo en pro de la privacidad del visitante. Incorporar sistemas de comentarios como 'Disqus' u otros suministra telemetría a terceros, es contrario a la privacidad y una falta de respeto al lector.
✉ Siéntanse libres de comentar, corregir o comunicar. Para ello pueden dirigirme un correo electrónico a hijosdeinit@protonmail.com. Pronto o tarde, siempre respondo.
♫ hijosdeinit - Canal de video en Odysee/lbry
♪ hijosdeinit - Podcast (en construcción)