HobbitOfShire
HobbitOfShire

Reputation: 2414

Using variables for paths in shell

I want to write a cript for a user to set an installation path. I am using this

read $file_path
cd $file_path

But it does not change to the path saved on that variable. How can i set this exactly because this seems the wrong way?

Upvotes: 0

Views: 92

Answers (2)

cdarke
cdarke

Reputation: 44344

Somewhat reading between the lines, I think you are trying to call a script which you expect to change directory of the caller: For example:

myscript:

read file_path
cd "$file_path"

command-line:

./myscript

and you find it hasn't changed the directory. That's because you are running the script in a child process. It changes the current directory of the child, then returns to the parent, which is unaffected.

You need to source the file instead, that is, run the commands in the current process, not a separate one:

. ./myscript

Yes, notice the extra 'dot' . at the start. This is generically known as the source command, and you can use source instead of 'dot' on bash and csh.

Upvotes: 1

fedorqui
fedorqui

Reputation: 289495

read does not use the $ to read the variable. Hence, it should be

read file_path
cd $file_path

Upvotes: 2

Related Questions