4

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
0

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.