-
BASH > mise en forme du texte dans un terminal
echo "Old line"; echo -en "\e[1A"; echo -e "\e[0K\r new line" echo -en "\e[7A\e[1;35m BASH \e[7B\e[6D"
CURSEUR
afficher / effacer le curseur
\e[25h ou tput cvvis ou tput cnorm # affiche curseur \e[25l ou tput civis # efface curseur
enregistrer / restaurer la position du curseur
\e[s ou tput sc # ENREGISTRE la position du curseur \e[u ou tput rc # RESTAURE la position du curseur
positionner à la ligne X et à la colonne Y
echo -e "\e[X;YH" echo -e "\e[X;YF" echo -e "\e[X;YG" tput cup X Y tput home positionne le curseur à son origine (0-0)
echo -e "\e[6G*" *
rester sur la même ligne
echo -n "blablabla" echo -e "\r${VAR}\c"
\rrevenir au début de la ligne,\cne pas aller à la ligne suivantetput cup 21 1 ; echo "[" tput cup 21 78 ; echo "]" i=2 while [ $i -ne 77 ] ; do tput cup 21 $i echo -ne "->" ((i++)) sleep 0.1 done [------> ]
déplacer de N lignes
\e[NA # déplace de N lignes vers le haut \e[NB # déplace vers le bas puts "\e[2E" # déplace au début de 2 lignes en bas puts "\e[4F" # déplace au début de 4 lignes en haut tput ll # dernière ligne, 1ère colonne tput cuu1 # déplace 1 ligne au-dessus
déplacer de N caractères
\e[NC ou tput cuf N # déplace de N caractères vers la droite \e[ND ou tput cub N # déplace de N caractères vers la gauche
déplacer de N caractères
$ echo -e "\033[6G*" *
Faire plusieurs choses :
(tput sc ; tput cup 23 45 ; echo "X" ; tput rc)scroll
puts "\e[2S" # scroll 2 lignes en haut puts "\e[4T" # scroll 4 lignes en bas
ÉCRAN
nombre de lignes et colonnes
tput linesrenvoie le nombre de lignes du terminaltput colsrenvoie le nombre de colonnes du terminaleffacer l'écran
\e[2J ou tput clear
tput smsoStart stand-outtput rmsoEnd stand-outRestaurer l'écran initial
Restaurer le terminal comme il était avant l’exécution d'un script :
1) On sauve le terminal :
tput smcup2) On efface le terminal :
clear3) On exécute le script :
... code ...4) On remet tous les paramètres par défaut :
tput sgr05) On retourne le terminal :
tput rmcupEFFACER
effacer des caractères
tput ech N # efface N caractères tput clear # efface l'écran et position du curseur à home tput el1 # efface du début de la ligne jusqu'au curseur tput el2 # efface la ligne entière (position du curseur inchangée) tput el ou echo -e \e[K # efface du curseur jusqu'à la fin de la ligne tput ed # efface du curseur jusqu'à la fin de l'écran echo \b # efface 1 caractère avant (backspace)
effacer une ligne
tput e1 \e[0K # efface du curseur jusqu'à la fin de la ligne \e[1K # efface du début de la ligne jusqu'au curseur \e[2K # efface la ligne entière
\e[0J # efface du curseur jusqu'à la fin de l'écran \e[1J # efface l'écran jusqu'au curseur \e[2J # efface l'écran entier
INSÉRER
tput ich N insert N caractères (et déplace le reste de la ligne) tput il N insert N lignes
RÉPÉTER UN CARACTÈRE
Afficher 15 fois la caractère
=
printf "=%.s" $(seq 15) ===============
VAR=15 printf "=%.s" $(seq $VAR) ===============
RÉPÉTER UN CARACTÈRE SUR TOUTE LA LIGNE
printf "%*s\n" "${COLUMNS:-$(tput cols)}" " " | tr ' ' _ printf "_%.s\n" $(seq $(tput cols)) printf "%$(tput cols)s\n" " "| tr ' ' _
ALIGNER DU TEXTE
Centrer
Rappel : Longueur d'une chaine :
${#VAR}- Longueur de la ligne du terminal :$(tput cols)ou${COLUMNS}PREMIÈRE MÉTHODE :
function centrer_term() { long=$(( ${tput cols} / 2 + ${#1} / 2 )) fin=$(( $(tput cols) - ${long} )) printf "%${long}s%${fin}s\n" "$1" " " } centrer_term "Ceci est un test"
DEUXIÈME MÉTHODE
awk '{ C=$(tput cols) ; L=length() ; G=int((C-L)/2) ; printf "%"(G+L)"s\n", $0 }'
ici, on calcule la longueur de
$0aveclength(). (length(var)retourne la longueur devar. Si cette dernière est absente, alors$0sera prise par défaut).Gcalcule combien d'espaces il faut insérer à gauche.Aligner à gauche
printf "%-Xs" "$VAR"
-Xcaractères avec des blancs à droiteprintf "%-10s |\n" "hello" ; printf "%-10s |\n" "123456789" hello | 123456789 |
Aligner à droite
printf "%Xs" "$VAR" printf "%7s" "toto" toto
Xcaractères avec des blancs à gaucheprintf "%A.Bs" "texte" printf "%5.3s" "abcdef" abc
A longueur de la nouvelle chaine en ajoutant des espaces à gauche. B nombre de caractères gardés de l'ancienne chaine.
awk '{ printf "%Xs\n", $0 }'
Aligner le texte à droite sur la Xème colonne
awk '{ printf "%Xs\n", $0 }' printf() formate la variable $0 and left pad it with spaces until the total length is 79 chars.
CAPITALISER / MINUSCULISER
add_mac="0:13:ce:7:7a:ad" printf "%02X:%02X:%02X:%02X:%02X:%02X" 0x${add_mac//:/ 0x} # tout en majuscule 00:13:CE:07:7A:AD printf "%02x:%02x:%02x:%02x:%02x:%02x" 0x${add_mac//:/ 0x} # tout en minuscule
COULEURS
echo et printf
echo -e "\e[police;couleur_texte;couleur_fondm..."
police: normal (0défaut), gras (1), non gras (21), souligné (4), non souligné (24), clignotant (5), non clignotant (25), inversé (7), non inversé (27)Pour accumuler des décorations => gras (
1) ET souligné (4) :echo -e "\e[1;4;34m"couleur_texte: Les couleurs vont de30à37(0ramène aux valeurs par défaut)couleur_fond: Les couleurs vont de40à47CODES COULEURS
COULEUR TEXTE ARRIÈRE-PLAN Noir 30 40 Rouge 31 41 Vert 32 42 Jaune 33 43 Bleu 34 44 Magenta 35 45 Cyan 36 46 Blanc 37 47
echo -e "\e[4;36;42mblabla" printf "\e[1;34mBleu\e[0m" printf '\e[1;34m%-6s\e[m' "Bleu"
UTILISATION DANS UN SCRIPT
gris='\e[1;30m' ; vert='\e[0;32m' ; neutre='\e[0;m' echo -e "${gris}blabla ${vert}coucou${neutre}" printf "\e[31;40m%s\e[0m" "blabla" } printf '\e[5;32;40m blabla\e[m\n' # texte qui clignotte
En fait, il faut passer les chaines à afficher en paramètres.
bleu=$(tput setaf 4) normal=$(tput sgr0) printf "%40s\n" "${bleu}Texte en bleu${normal}"
tput
tput setaf couleur_texte tput setab couleur_fond
CODE COULEUR :
0noir -1rouge -2vert -3jaune -4bleu -5magenta -6cyan -7blanctput boldgras -tput dimsombretput smulsouligné -tput rmulstop soulignétput sitmitalique -tput ritmstop italiquetput blinkclignotanttput revinverse vidéotput smsoenter standout mode (bold on rxvt)tput rmsoexit standout modeRETOUR A LA NORMAL :
tput sgr0MODIFIER LE PROMPT
fichier ~/.bashrc, voire /etc/bashrc, puis taper
source ~/.bashrcpour le recharger sans redémarrer.NOIR=$(tput setaf 0) ; ROUGE=$(tput setaf 1) ; VERT=$(tput setaf 2) ; JAUNE_VIF=$(tput setaf 190) JAUNE=$(tput setaf 3); BLEU_VIF=$(tput setaf 153) ; BLEU=$(tput setaf 4) ; MAGENTA=$(tput setaf 5) CYAN=$(tput setaf 6) ; BLANC=$(tput setaf 7) ; GRAS=$(tput bold) ; NORMAL=$(tput sgr0) CLIGNOTE=$(tput blink) ; REVERSE=$(tput smso) ; SOULIGNE=$(tput smul) PS1='\[$JAUNE\]\u\[$BLANC\]@\[$VERT\]\h\[$NORMAL\]:\[$ROUGE\] \w\n\[$CYAN\]\$\[$NORMAL\] '
PS1La variable de l’invite de commande -u: nom de l’utilisateur -h: hostname de la machine -w: dossier courant -n: saut de ligneFIGLET
__ _ _ _ / _(_) __ | | ___| |_ | |_| |/ _ `| |/ _ \ __| | _| | (_| | | __/ |_ |_| |_|\__, |_|\___|\__| |___/
Installation :
sudo apt-get install figletExemple :
figlet ti1EXEMPLES
Hardcoded colors
printf ‘%b\n’ ‘Bla \e[31mBla\e[39m Bla \e[32mBla\e[39mBla'tput et echo
echo "Du texte en $(tput setaf 1)rouge." ROUGE="$(tput setaf 1)" echo "Du texte en ${ROUGE}rouge."
Créer un index
pad=$(printf '%0.1s' "-"{1..60}) padlength=40 string2='bbbbbbb' for string1 in a aa aaaa aaaaaaaa ; do printf '%s' "$string1" printf '%*.*s' 0 $(( padlength - ${#string1} - ${#string2} )) "$pad" printf '%s\n' "$string2" string2=${string2:1} done a--------------------------------bbbbbbb aa--------------------------------bbbbbb aaaa-------------------------------bbbbb aaaaaaaa----------------------------bbbb
Without subtracting the length of the second string:
a---------------------------------------bbbbbbb aa--------------------------------------bbbbbb aaaa------------------------------------bbbbb aaaaaaaa--------------------------------bbbb
printf '%*.*s' ...The first asterisk is replaced by the zero in the argument list. The second asterisk is replaced by the result of the calculation in the second argument. The result, for the strings "aaaa" and "bbbbb", for example, is '%0.31s'. The string (the final argument) is truncated to the length specified after the dot. The zero prevents any space padding from being output. So 31 hyphens are output.---
Use the length of the value of 'PROC_NAME' as offset for the fixed string 'line':
line='----------------------------------------' PROC_NAME='abc' printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}" PROC_NAME=’abcdef’ printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}" abc ————————————- [UP] abcdef ———————————- [UP]
---
printf "%5.5s\n" abc abc printf "%5.5s\n" abcdefghij abcde printf "%5s\n" abc abc printf "%5s\n" abcdefghij abcdefghij printf '%*s' 20 hello hello
TITRE DE LA FENÊTRE Xterm
function proml { case $TERM in xterm*) local TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) local TITLEBAR='' ;; esac PS1="${TITLEBAR}[\$(date +%H%M)][\u@\h:\w]\$ " PS2='> ' PS4='+ ' }
This is a function that can be incorporated into ~/.bashrc. The function name could then be called to execute the function. The function, like the PS1 string, is stored in the environment. Once the PS1 string is set by the function, you can remove the function from the environment with unset proml. Since the prompt can't change from being in an Xterm to being at the console, the TERM variable isn't tested every time the prompt is generated. I used continuation markers (backslashes) in the definition of the prompt, to allow it to be continued on multiple lines. This improves readability, making it easier to modify and debug.
The first step in creating this prompt is to test if the shell we're starting is an xterm or not: if it is, the shell variable (${TITLEBAR}) is defined. It consists of the appropriate escape sequences, and \u@\h:\w, which puts <user>@<machine>:<working directory> in the Xterm title bar. This is particularly useful with minimized Xterms, making them more rapidly identifiable. The other material in this prompt should be familiar from previous prompts we've created.
The only drawback to manipulating the Xterm title bar like this occurs when you log into a system on which you haven't set up the title bar hack: the Xterm will continue to show the information from the previous system that had the title bar hack in place.
on setting the window title of the Xterm and the title of the corresponding icon separately. He uses this under WindowMaker because the title that's appropriate for an Xterm is usually too long for a 64x64 icon. "\[\e]1;icon-title\007\e]2;main-title\007\]". He says to set this in the prompt command because "I tried putting the string in PS1, but it causes flickering under some window managers because it results in setting the prompt multiple times when you are editing a multi-line command (at least under bash 1.4.x -- and I was too lazy to fully explore the reasons behind it)." I had no trouble with it in the PS1 string, but didn't use any multi-line commands. He also points out that it works under xterm, xwsh, and dtterm, but not gnome-terminal (which uses only the main title). I also found it to work with rxvt, but not kterm.
man terminfowill give you a huge list of capabilities---
rester au début de la même ligne
sans effacer la ligne :
printf "89%%"; sleep 1; printf "\r90%%\n"
en effaçant la ligne :
printf "89%%"; sleep 1; printf "\e[3D90%%\n"
\e[3D to move three characters to the left, and writes over them
printf "89%% hello"; sleep 1; printf "\e[0E\e[K90%%\n"
\e[0E to move to the beginning of the current line, and \e[K to clear to the end of the line.
tput cub (cursor back) - tput el (erase line)
printf "89%%"; sleep 1; tput cub 3; tput el; printf "90%%\n"
printf "89%% hello"; sleep 1; tput hpa 0; tput el; printf "90%%\n"
move the cursor to the left-most column (hpa 0) and clear to the end of the line.
---