Using echo

A quick guide on how to use the echo command in the most practical way possible.

man is very direct in saying that the echo command is used to repeat arguments to std out. And that means passing practically anything to standard output. With echo we can use escape characters, such as tabulation, new line, activate text colors, background, character decoration, etc.

Escape

Without -e, it can’t interpret escaped commands.

$ echo "Oi\nEu sou o Echo."
Oi\nEu sou o Echo.

With -e, you enable the interpretation of escaped characters, such as \n to skip lines:

$ echo -e "Oi\nEu sou o Echo."
Oi
Eu sou o Echo.

For a new column , use the -e option with \v:

$ Nome="Echo"
$ echo -e "Oi\nSeu nome é $Nome \v$Nome \v$Nome"
Oi
Seu nome é Echo
                  Echo
                         Echo

To re-tab use the -e option with \t:

$ echo -e "\tOlá,\n\tEste é um texto tabulado."
    Olá,
    Este é um texto tabulado.

Avoid newline

If you don’t set the -n option, the information will be displayed on the screen, then a new line will appear:

$ echo "Oi, digite seu nome: "; read nome
Oi, digite seu nome: 
_

Now, with -n, we no longer have a newline after the sentence:

$ echo -n "Oi, digite seu nome: "; read nome
Oi, digite seu nome: _ 

This new line that echo creates can get in the way when it comes to getting the hexadecimal of a character

$ echo -e A |hexdump
0000000 41 0a <----- olha o newline aqui no 0a, atrapalhando
0000002

$ echo -en A |hexdump
0000000 41 <----- agora, só o hex 41, que é o A em ascii
0000001

Do you have any suggestions on how to use echo? Send it to me in the comments and I’ll insert it here =D

Sobre o autor

Comentários

Mais artigos