Newbie trying to use sources

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

Ktate

Posted 2019-12-31T20:08:49.153

Reputation: 3

Answers

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.

Spiff

Posted 2019-12-31T20:08:49.153

Reputation: 84 656

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 – 2019-12-31T20:33:39.077

@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. – Kamil Maciorowski – 2019-12-31T21:21:01.570

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.

harrymc

Posted 2019-12-31T20:08:49.153

Reputation: 306 093

so either way, I still have to source it to make the cd affect the working shell. Thanks! – Ktate – 2019-12-31T23:33:48.803