Shell - Write variable contents to a file
I would like to copy the contents of a variable (here called
var) into a file.
The name of the file is stored in another variable
I'm having problems doing this. Here's what I've tried:
cp $var $destfile
I've also tried the same thing with the dd command... Obviously the shell thought that
$var was referring to a directory and so told me that the directory could not be found.
How do I get around this?
var="text to append"; destdir=/some/directory/path/filename if [ -f "$destdir" ] then echo "$var" > "$destdir" fi
if tests that
$destdir represents a file.
> appends the text after truncating the file. If you only want to append the text in
$var to the file existing contents, then use
echo "$var" >> "$destdir"
cp command is used for copying files (to files), not for writing text to a file.