Resolving a parameter which is passed as parameter

Hi,
I have the following files.
->cat scr.sh

export TMP_DIR=/home/user/folder1
export TMP_DIR_2=/home/user/folder2
while read line
do
cat "$line"
done<file_list.dat

------------------------
-> cat file_list.dat

$TMP_DIR/file1.txt
$TMP_DIR_2/file2.txt

---------------------------
-> cat /home/user/folder1/file1.txt

This is data from file1

---------------------------
-> cat /home/user/folder2/file2.txt

This is data from file2

-------------------------------
**************************************************
In the above code when I execute the scr.sh file, variable $TMP_DIR and $TMP_DIR_2 are not getting resolved. instead the error it shows file not available:$TMP_DIR/file1.txt .
My objective is to get the content of file1 and file2 inside scr.sh for further processing.
Could someone please help me on this.

Thanks in advance
TSB

You can force the shell to re-evaluate a string using eval , e.g.:

cat $(eval echo $line)
1 Like

Thanks a lot.
This worked.

Please be aware that eval is deprecated and dangerous.

Nevertheless, you can simplify above to

eval cat "$line"

Hi,

When I use

eval cat "$line"
or
cat $(eval echo $line) 

and my filename contains spaces - I get the following error - " No such file or directory"

For Ex:

-> cat filelist.dat

$TMP_DIR/file f1.txt

It throws the following:

cat: /home/user/folder1/file: No such file or directory
cat: f1.dat: No such file or directory

Where as when I use cat "file f1.txt" it works, though without $TMP_DIR. But my objective is to attain $TMP_DIR resolution and file expansion.

Can you plz help on this?

Thanks in advance
TSB

As you've noted, you need to quote the string to supply a pathname containing spaces. The same still applies when you're using a variable.

cat "$(eval echo \"$line\")"

Technically, the extra quotes around $line aren't necessary for your example case but if you want to preserve other whitespace then you will need them (without them echo will receive 2 arguments, which it will print with a space separator),

1 Like
eval cat \"$line\"
1 Like