For loop using input file doesn't expand variables

Hi,

I'm using a for loop reading from an input file that contains files, whose path includes a variable name.

But the for loop doesn't expand the variable and therefore can't find the file.

Here's an example:

            File BACKUPFILES
/home/John/alpha
/home/Sue/beta
$BACKUP/listing/gamma
for i in `cat BACKUPFILES`
do
  file $i
done
           Output
/home/John/alpha:   ascii text

/home/Sue/beta:   ascii text
$BACKUP/listing/gamma:       cannot open: No such file or directory

The variable is set correctly - if I run echo $BACKUP in the for loop, it displays it correctly.

Does anyone know how to get around this? Thanks

could you mention where u set the variable value (BACKUP)???
use tag..( in tool bar use # symbol )

thanks

BACKUP is a variable set globally at login - it's not in /etc/profile, but all users process a login script that sets this and other variables.

try this:

for i in `cat BACKUPFILES`
do
  file $(eval echo $i)
done

another, more efficient approach may be:

while read i
do
 file $(eval echo $i)
done < BACKUPFILES

Great - both solution worked. Thanks for your help - but could you tell me why the second solution is more efficient than the first? I've got into the habit of using for loops.

Nothing but this avoids creating an extra process with calling an external command (cat).

"While read" the thing for these kind of purpose. ( reading file ).

OK - will remember that. Thanks for your help.

It also prevents problems should BACKUPFILES exceed the maximum size your shell allows for variables. This and related programming mistakes are described in more detail here.

1 Like

set BAKCUPFILES="/home/xyz/abc /home/xyz/prq"

use cat as mentoned above and check it.