Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
Writing variables to file with bash

I'm trying to configure a file with a bash script. And the variables in the bash script are not written in file as it is written in script.

Ex:

#!/bin/bash

printf "%s" "template("$DATE\t$HOST\t$PRIORITY\t$MSG\n")" >> /file.txt

exit 0

This results to template('tttn') instead of template("$DATE\t$HOST\t$PRIORITY\t$MSG\n in file.

How do I write in the script so that the result is template("$DATE\t$HOST\t$PRIORITY\t$MSG\n in the configured file?

Is it possible to write variable as it looks in script to file?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Enclose the strings you want to write within single quotes to avoid variable replacement.

> FOO=bar
> echo "$FOO"
bar
> echo '$FOO'
$FOO
> 
over 4 years ago · Santiago Trujillo Relatório

0

Using printf in any shell script is uncommon, just use echo with the -e option. It allows you to use ANSI C metacharacters, like \t or \n. The \n at the end however isn't necessary, as echo will add one itself.

echo -e "template(${DATE}\t${HOST}\t${PRIORITY}\t${MSG})" >> file.txt

The problem with what you've written is, that ANSI C metacharacters, like \t can only be used in the first parameter to printf.

So it would have to be something like:

printf 'template(%s\t%s\t%s\t%s)\n' ${DATE} ${HOST} ${PRIORITY} ${MSG} >> file.txt

But I hope we both agree, that this is very hard on the eyes.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda