8 ms·
Standardness notwithstanding, using tput is more readable and memorable. I can type this from memory: echo "I'm $(tput setaf 4)blue$(tput sgr0)." but I co
by rbonvall 5y ago
Standardness notwithstanding, using tput is more readable and memorable. I can type this from memory:
echo "I'm $(tput setaf 4)blue$(tput sgr0)."
but I couldn't get this one right without looking it up:
echo -e "I'm \033[0;34mblue\033[0m."
- deleted 5y ago[deleted]
- faho 5y agoStill not particularly readable or memorable. You still need to remember that blue is color number 4 and that "sgr0" is "exit_attribute_mode", what you might call "reset".
- tomc1985 5y agoStore the sequences in variables and put those instead. You get readability and locality!
- nick__m 5y agoI was about to post the exact same reply so I will post it as an example: #!/bin/sh BLUE=$(tput setaf 4) RST=$(tput sgr0) echo "I'm ${BLUE}blue${RST}."
- junon 5y agoBecause you're using a lot more characters than you need. echo -e "I'm \e[34mblue\e[m." However, `tput` is definitely the more 'correct' approach. What actual benefit it affords you over the hardcoded escapes is left to edge-cases and very, very old or otherwise niche terminal emulators. By the way, the `3x` means foreground, the `4x` means background. `x` is a number between 0 and 7 (inclusive) that indicates the color. `x=8` means "extended"/non-standard and generally takes a few more control codes afterward, and `x=9` means "reset". If you know binary, you can remember the 0-7 colors. It's a 3-bit code corresponding to BGR (where B is the MSB). BGR 000 = 0 = black 001 = 1 = red 010 = 2 = green 011 = 3 = yellow 100 = 4 = blue 101 = 5 = magenta 110 = 6 = cyan 111 = 7 = white You can also add 60 to the code to make it "bright", e.g. red foreground (31) can be made bright red by adding 31+60=91. Same can be applied to backgrounds (4x+60=10x). The bright codes are less supported though admittedly I've never seen a modern emulator that doesn't. It also gives you bright colors on old Windows cmd.exe prompts without needing the bold mode (1).
- mmphosis 5y agoalias red='echo -ne "\e[31m"' alias yellow='echo -ne "\e[33m"' alias green='echo -ne "\e[32m"' alias blue='echo -ne "\e[34m"' alias cyan='echo -ne "\e[36m"' alias violet='echo -ne "\e[35m"' alias grey='echo -ne "\e[90m"' alias gray='echo -ne "\e[90m"' alias white='echo -ne "\e[37m"' alias bold='echo -ne "\e[1m"' alias flash='echo -ne "\e[7m\e[5m"' alias normal='echo -ne "\e(B\e[m"'