Write text in Shell Script

1

I'm doing a Shell Script, and I have to write a lot of lines in a single file, how can I do it in a more automatic way? Well I started doing it in a very manual way:

echo "primeira linha do arquivo" >> /diretorio/arquivo.txt
echo "segunda linha do arquivo" >> /diretorio/arquivo.txt

Can I put all rows in a single command? Example:

echo "primeira linha
segunda linha
terceira linha
quarta linha
" >> /diretorio/arquivo.txt

But there is something else, I have some variables in my script that I need to be putting in those lines where they will be written, getting more like this:

variavel1=primeira
variavel2=segunda
variavel3=terceira

echo "$variavel1 linha
$variavel2 linha
$variavel3 linha
quarta linha
" >> /diretorio/arquivo.txt

I've looked everywhere, but I have not found anything related to it.

    
asked by anonymous 27.11.2018 / 00:18

2 answers

2

There are several ways, one is using the command cat and a delimiter:

cat >'arquivo.txt' <<EOT
aí você coloca
um monte de texto
e só precisa terminar
com o a mesma string usada
no delimitador.
EOT

Another is using a function inside Bash :

function coisas_a_imprimir(){
    echo "a"
    echo "b"
}

coisas_a_imprimir > 'arquivo.txt'

What I consider to be most "clean" in Bash is to use a subshell :

saida='arquivo.txt'

let variavel_1=1
let variavel_2=2

( echo "Isto é um exemplo de subshell"
  echo ${variavel_1}
  let variavel_2=3
  echo ${variavel_2} ) >$saida

echo $variavel_2

The only "problem" in this case is scope because variables created and / or changed within it will not be transferred to the main shell - see in the example content variavel_2 inside and out of the subshell .

    
27.11.2018 / 01:05
0

You can use the -e option of echo , which allows \n to be set and these are interpreted as line breaks:

echo -e "$variavel1 linha\n$variavel2 linha\n$variavel3 linha\nquarta linha"

Another option is to use the command printf , which also accepts \n for line breaks:

printf "$variavel1 linha\n$variavel2 linha\n$variavel3 linha\nquarta linha"

The difference is that echo adds an "extra" line break at the end (in this case, after "fourth line"), whereas printf does not (this would need to have an explicit \n at the end) .

You can make echo do not add the line break at the end with the -n option:

echo -ne "$variavel1 linha\n$variavel2 linha\n$variavel3 linha\nquarta linha"

There are still other differences between these two commands, and you can see this link for more details.

    
27.11.2018 / 13:40