1

contents of origlist

$var1
$var4
$var3
$var2

contents of testparsher.sh

#!/bin/bash

var1="Smith^John"
var2="998877"
var3="member"
var4="12"
cat /dev/null > file.txt

filename=origlist

while read line; do

   echo $line >> file.txt

done < "$filename"

the file.txt I want is:

Smith^John
12
member
998877

the file.txt I'm getting is

$var1
$var4
$var3
$var2

So what's the syntax to get the loop to see the parsed text as the preloaded variables?

Thank you so much for your time.

3 Answers 3

2

You can do this without 'eval' by using "indirect expansion" (see the Bash manual page for an explanation):

while read var || [[ $var ]] ; do
    varname=${var#$}
    printf '%s\n' "${!varname}"
done <"$filename" >file.txt

The '[[ $var ]]' is necessary to allow for an unterminated last line in the input file.

The '$' has to be removed from the variable name. Does it need to be in the input file?

Use 'printf' instead of 'echo' in case the variable value begins with an 'echo option.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 This is much safer, as using eval introduces a huge security risk if the contents of the input file are modified. Using indirect parameter expansion, the worst that can happen is that unexpected input will cause a bad substitution error.
1

you need to use eval :

#!/bin/bash

var1="Smith^John"
var2="998877"
var3="member"
var4="12"
cat /dev/null > file.txt

filename=origlist

while read line; do
   eval echo $line >> file.txt
done < "$filename"

2 Comments

Thank you so much!!!! All I had to do was add eval. I can't believe I couldn't find this anywhere. thank you
The use of eval here is strongly discouraged. Arbitrary code could be inserted into origlist, and this code will happily execute it.
0

You are looking for eval, but it comes with a lot of caveats.

Or perhaps you are looking for a here document.

cat <<____HERE >file.txt
$var1
$var4
$var3
$var2
____HERE

1 Comment

The here document won't help; I think file.txt exists prior to the variables it references being set.

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.