linuxbashshell

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 destfile.

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?


Solution

  • Use the echo command:

    var="text to append";
    destdir=/some/directory/path/filename
    
    if [ -f "$destdir" ]
    then 
        echo "$var" > "$destdir"
    fi
    

    The if tests that $destdir represents a file.

    The > appends the text after truncating the file. If you only want to append the text in $var to the file existing contents, then use >> instead:

    echo "$var" >> "$destdir"
    

    The cp command is used for copying files (to files), not for writing text to a file.