Reputation: 36372
I am new to shell scripting. I need to read a file that works in all shells that has variables defined in it. Something like:
variable1=test1
variable2=test2
....
I have to read this file line by line and prepare new string separated by spaces, like:
variable=variable1=test1 variable2=test2 ....
I tried with the below code:
while read LINE
do
$VAR="$VAR $LINE"
done < test.dat
but it's throwing me this error:
command not found Test.sh: line 3: = variable1=test1
Upvotes: 4
Views: 17320
Reputation: 85775
The problem with your script is the leading $
before var
is initialized, try:
#/bin/bash
while read line; do
var="$var $line"
done < file
echo "$var"
However you can do this with the tr
command by substituting the newline character with a space.
$ tr '\n' ' ' < file
variable1=test1 variable2=test2
$ var="$(tr '\n' ' ' < file)"
$ echo "$var"
variable1=test1 variable2=test2
Upvotes: 5
Reputation: 4038
When defining a shell variable you must omit the $. So VAR="bla"
is right, $VAR="bla"
is wrong. The $ is only necessary for using the variable, as in echo $VAR
;
while read LINE
do
VAR="$VAR $LINE"
done < test.dat
Upvotes: 4