0

I have a file which contains key/value -pairs in the format

TAG PATH

. Now, I want to write a program that reads from the command line a TAG, and changes the current working directory of invoking bash to corresponding PATH.

How would I go about this?

coderodde
  • 1,269
  • 4
  • 17
  • 34
  • "changes the current working directory of invoking bash" - Nope, try again. – Kevin Sep 03 '13 at 04:18
  • @Kevin Nope, I don't understand what you mean. – coderodde Sep 03 '13 at 04:30
  • 1
    It is impossible for a process to change its parent's environment, including the cwd. – Kevin Sep 03 '13 at 04:32
  • 2
    You can look into writing a script you can source, or a shell function to put in your bashrc, however, as they run in the active shell. – Kevin Sep 03 '13 at 04:34
  • 1
    @corerodde, Please add to your question more information. You want to make 'cd' to PATH, if current line contains 'TAG' word? – akozin Sep 03 '13 at 06:04

1 Answers1

1

You might consider something like (perhaps in your bash function)

while read tagname dirname ; do
   pushd $dirname ;
   dosomethingwith $tagname
   popd
done < yourinputfile.txt

See this question (about read in bash) and read the advanced bash scripting guide

GNU awk might be a better tool.

Notice that you can only change the current directory of the current process using the chdir(2) syscall (invoked by cd or pushd or popd bash builtins). There is no way to change the directory of some other process (e.g. the parent or invoking one). The pushd and popd builtins also updates bash directory stack.

There is no way to change the current directory of the invoking shell (the parent process running in a terminal). But you may define your own bash function there. Read Advanced Linux Programming to understand more about Unix processes

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547