-2

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.

1 Answers1

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 '19 at 20:11
  • Like cd /usr/src && make && make install – Raul Chiarella Jul 10 '19 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 '19 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 Says 'Reinstate Monica' Jul 10 '19 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 '19 at 21:03
  • Since the commands i need to do are pretty large, i made a function called cdZDir that does cd /usr/src; make; make install; and also workeeed. Thank you so much, appreciate it. Couldn't find the answer on that "duplicate" one – Raul Chiarella Jul 11 '19 at 21:05
  • You’re welcome.  Since my answer helped you, please “accept” it by clicking on the checkmark (below the voting buttons). – G-Man Says 'Reinstate Monica' Jul 11 '19 at 21:24
  • oh Sorry, i forgot. Just did it, thanks again! – Raul Chiarella Jul 12 '19 at 12:23