2

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?

3 Answers 3

3

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

> FOO=bar
> echo "$FOO"
bar
> echo '$FOO'
$FOO
> 
Sign up to request clarification or add additional context in comments.

1 Comment

Since the question is, "Writing variables to file in bash", it would be helpful (to those who end up here when searching for "write variable to file") if your example included writing the variable's value to a file.
2

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.

Comments

1

There are several escaping issues and the power of printf has not been used, try

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

Reasons for this separate answer:

  • The accepted answer does not fit the title of the question (see comment).
  • The post with the right answer
    • contains wrong claims about echo vs printf as of this post and
    • is not robust against whitespace in the values.
  • The edit queue is full at the moment.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.