0

I am trying to have a simple file which changes the directory where the user currently is. If I run the file using . ./Genesis then the source files works fine. But I want to just use ./Genesis and have the cd command work. I am in my root/Scripts folder: kyle@computer:~/Scripts

How can I modify the code to do this?

I have a file called Genesis which calls a source file

#!/bin/bash
#Genesis
. ./Genesis.sh

The Genesis.sh file has the following code:

jhome() {
cd ~/Scripts/dungeon
}
jhome

2 Answers 2

1

If you run a shell script normally instead of sourcing it, it runs in a sub-shell and can't affect your current shell. If you want it to change the current working directory of the shell from which you call it, you must source it instead. That's why sourcing exists.

2
  • I believe that is what I was trying to do. But I must be doing something wrong in one or both of my files.
    – Ktate
    Dec 31, 2019 at 20:33
  • @Ktate Clarification. You're sourcing Genesis.sh, which does change the working directory of the shell interpreting Genesis. The same shell interprets both files, true. The point is the shell interpreting Genesis is not the shell you type ./Genesis in, because you're not sourcing Genesis. You already observed if you source Genesis then cd will affect your current shell. Your current shell is the only shell in this case. When you run ./Genesis (as opposed to . ./Genesis), you run another shell. No matter if and what you source deeper, it's not your current shell. Dec 31, 2019 at 21:21
0

To achieve your goal, you should look for another means than executing a shell script which executes in its own shell, not affecting the caller's shell.

You could instead do one of the following:

  • Put the jhome function in the .bashrc file and call it instead of the script.
  • Add an alias in .bashrc : alias Genesis='cd ~/Scripts/dungeon'.
  • Execute the script via source : . ./Genesis.
1
  • so either way, I still have to source it to make the cd affect the working shell. Thanks!
    – Ktate
    Dec 31, 2019 at 23:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .