Reputation: 1086
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
Upvotes: 0
Views: 5322
Reputation: 27553
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.
Upvotes: 4
Reputation: 342273
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
Upvotes: 3
Reputation: 76541
Change "ls $file" to "eval ls $file" to get the shell to do its expansion.
Upvotes: 1