Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script read a file line by line

Tags:

bash

shell

unix

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
like image 509
Lolly Avatar asked Jan 15 '23 14:01

Lolly


1 Answers

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
like image 125
Chris Seymour Avatar answered Jan 20 '23 10:01

Chris Seymour