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?

1
  • If setup_top and CFG are relative paths, you need to include a cd .. at the end of your loop. Commented Oct 21, 2020 at 8:41

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

5 Comments

Thank Veyret for answering me. You gave me two answers. Unfortunatly I had same wrong answer after changing the line. Only two "------------" are the things I got from terminal.
when I tried Bourne-Again Shell Script, ASCII text executable, it failed. But When I tried Bourne-Again Shell Script, UTF-8 unicode text executable, it works!!! Thanks!!!!
@SatthewSeongHunMoon What else do you expect?! cd doesn’t print anything.
Nah What I wanted to say was When I execute that line, It shoild be moved to $setup_top or $CFG. But it didn't move at all
@SatthewSeongHunMoon How did you verify that? You can’t ‘see’ the working directory changing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.