-2

This question already has an answer here:

File name: Test.sh

#!/bin/bash

ZDir="$(echo /usr/src)"
cd "$ZDir"

When I execute the script ./Test.sh, the command cd doesn't do anything.  If I try to do it directly in the bash terminal, it works like a charm. Also, echo, used inside and outside the script, returns me the correct value (/usr/src).

Does anyone know why this happens? Again: cd $ZDir works if used outside the script, directly in the terminal...

Edit: Could'nt find the answer on the "duplicate" one but that G-Man user right there answered exactly what i needed to do. Just included a && followed by the next command i needed to do and worked. Functions can also be used for this... cdZDir() { cd /usr/src; make; make install; }

Then just call in the function.

marked as duplicate by roaima, muru, glenn jackman bash Jul 10 at 2:17

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

cd only affects the current shell and its descendants.  Shell scripts are run in new shell processes, so a cd in a script affects only the remainder of the execution of the script, and any programs it runs.

  • If you put commands like pwd and ls into the script, after the cd, you’ll see that the cd has succeeded in the script.
  • If you say . ./Test.sh, your current (main) shell process will read Test.sh and execute the commands therein.  Then you’ll see that your current (main) shell process will be in the new directory.
  • Well, i need to do a make install inside a directory and i can't do it if cd does'nt go to that directory. – Raul Chiarella Jul 10 at 20:11
  • Like cd /usr/src && make && make install – Raul Chiarella Jul 10 at 20:12
  • I asked a new question because the one listed as 'already answered' did'nt helped me. I don't get it. I don't know how to source the script ". ./script" – Raul Chiarella Jul 10 at 20:18
  • (1) It seems that what you want to do is to put the entire cd /usr/src && make && make install command line into the script.  (2) What’s there to know? You type a dot (.). You type a space (⁠ ⁠). You type the name of the script (with or without the ./). And you press “Enter”. – G-Man Jul 10 at 20:30
  • Hey G-Man. Thank you! Based on what u just said, i did using && on the same line and worked like a charm! – Raul Chiarella Jul 11 at 21:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.