Writing variables to file with bash

Issue

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?

Solution

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

> FOO=bar
> echo "$FOO"
bar
> echo '$FOO'
$FOO
> 

Answered By – Didier Trosset

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published