Can I store file contents to a variable in a shell script?
sh, shell, solaris
Solution
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 5
FINISHED=`date`
#
echo "Script start time: $STARTED"
echo "Script finish time: $FINISHED"
If I run this simple script, I see the following:
ubuntu$ /tmp/1.sh
Script start time: Wed May 7 04:56:51 CDT 2008
Script 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 qouteProblem
Say I have a file file.txt with data (say '100') in it. I want to read the contents of this file to a variable for future processing. I want this to work on both Linux and Solaris. How can I do this?