Write text to Shell Script

Asked

Viewed 3,774 times

2

I am making a Shell Script, and I have to record a lot of lines in a single file, how can I do this more automatically? 'Cause 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

Is it possible to put all lines 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 these lines that will be recorded, getting more like this:

variavel1=primeira
variavel2=segunda
variavel3=terceira

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

I’ve searched everywhere, but I can’t find anything related to that.

  • It would be nice to say what the command cat makes or posts a link with the explanation

3 answers

3

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 within the Bash:

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

coisas_a_imprimir > 'arquivo.txt'

The one I consider the most "clean" in Bash is using 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 the one of scope because the variables created and/or changed within it will not be transferred to the shell main -- see in the example the contents of variavel_2 inside and outside the subshell.

0

You can use the option -e of echo, which allows them to be placed \n 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, who also accepts \n for line breaks:

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

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

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

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.

0

You can use exec:

#!/bin/bash

exec 1>> text.txt


#Echos

echo "foo"
echo "bar"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.