Shell script reads file line by line

I am new to shell scripting . I need to read a file that works in all shells with the variables defined in it. Sort of:

 variable1=test1 variable2=test2 .... 

I need to read this file line by line and prepare a new line, separated by spaces, for example:

 variable=variable1=test1 variable2=test2 .... 

I tried with the code below:

 while read LINE do $VAR="$VAR $LINE" done < test.dat 

but he throws me this error:

 command not found Test.sh: line 3: = variable1=test1 
+4
source share
2 answers

The problem with your script is leading $ before var initialization, try:

 #/bin/bash while read line; do var="$var $line" done < file echo "$var" 

However, you can do this with the tr command, replacing the newline with a space.

 $ tr '\n' ' ' < file variable1=test1 variable2=test2 $ var="$(tr '\n' ' ' < file)" $ echo "$var" variable1=test1 variable2=test2 
+5
source

When defining a shell variable, you must omit $. So VAR="bla" right, $VAR="bla" is wrong. The value of $ is only necessary for using the variable, as in echo $VAR ;

 while read LINE do VAR="$VAR $LINE" done < test.dat 
+4
source

All Articles