tags:

views:

153

answers:

3

I have a file "FileList.txt" with this text:

/home/myusername/file1.txt
~/file2.txt
${HOME}/file3.txt

All 3 files exist in my home directory. I want to process each file in the list from a bash script. Here is a simplified example:

LIST=`cat FileList.txt`
for file in $LIST
do
  echo $file
  ls $file
done

When I run the script, I get this output:

/home/myusername/file1.txt
/home/myusername/file1.txt
~/file2.txt
ls: ~/file2.txt: No such file or directory
${HOME}/file3.txt
ls: ${HOME}/file3.txt: No such file or directory

As you can see, file1.txt works fine. But the other 2 files do not work. I think it is because the "${HOME}" variable does not get resolved to "/home/myusername/". I have tried lots of things with no success, does anyone know how to fix this?

Thanks,

-Ben

+3  A: 

Use eval:

while read file ; do
  eval echo $file
  eval ls $file
done < FileList.txt

From the bash manpage regarding the eval command:

The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0.

jheddings
+1  A: 

Change "ls $file" to "eval ls $file" to get the shell to do its expansion.

R Samuel Klatchko
+2  A: 

you will hit "spaces problem" using the for loop with cat. Manipulate IFS, or use a while read loop instead

while read -r line; do eval ls "$line"; done < file
ghostdog74
+1 That is a better approach to reading the file... I've updated my answer as well.
jheddings