Can I store file contents to a variable in a shell script? Can I store file contents to a variable in a shell script? shell shell

Can I store file contents to a variable in a shell script?


Try this line:

VAR=$(cat file.txt)

or

VAR=$(head -1 file.txt)

EDIT 1:

Using output of Unix commands to set variables

One of the best things about shell scripting is that it's very easy to use any Unix command to generate the output and use it to set the variable.

In this example, I'm running a date command and saving its output as values for my variables:

#!/bin/sh#STARTED=`date`sleep 5FINISHED=`date`#echo "Script start time: $STARTED"echo "Script finish time: $FINISHED"

If I run this simple script, I see the following:

ubuntu$ /tmp/1.shScript start time: Wed May 7 04:56:51 CDT 2008Script finish time: Wed May 7 04:56:56 CDT 2008

The same approach can be used for practically any scenario.

so the mvp's answer will works on any unix shell:

F=`cat file.txt`

Just try with backtick ` not ' single qoute


This should work:

 VAR=`cat file.txt`

If you want to get only first line of file, use this:

 VAR=`head -1 file.txt`


Have you tried the following

VAR=$(<file)

It worked when I needed the second line in a two line file to store as a variable in bash.