0

I have 2 files. One is list file named envlist. Another one is shell script file named test.

In envlist(list file), there's the environment variable list as below ;

setup_top
CFG

those are already declared as the environment variable.

(So when I type cd $setup_top or cd $CFG in command, it works well)

And in test(shell script), there's the code as below ;

#!/bin/bash

dir=$(<$env/envlist)     # $env is another environment variable I declared.
for i in ${dir[*]}
do
     cd $i               # I think this line is a matter.
     echo "------------------"
     sleep 2
done

When I executed this shell script, I got the error as below;

./test: line 6: cd: setup_top: No such file or directory
----------------------------
./test: line 6: cd: CFG: No such file or directory
----------------------------

reading envlist file line by line seems to work well, but cd command seems not to work.

How can I fix the shell script code to work fine?

Biffen
  • 6,249
  • 6
  • 28
  • 36

1 Answers1

0

Actually, you need to transform $i into the name of the variable, then read $varname. If the shell would support this, you should write cd $$i. Unfortunately, this will not work, because $$ gives the current PID.

As suggested by @Biffen, you should use shell variable substitution:

cd ${!i}

Previous answer, using dangerous eval instruction:

eval cd \$$i

Note: eval is a dangerous instruction. Use it only if you are sure of the content of your files (not files provided by untrusted users).

Stéphane Veyret
  • 1,791
  • 1
  • 8
  • 15