Christopher Shroba
Christopher Shroba

Reputation: 7584

Linux change directory from an executable bash file

I have a file in /usr/bin called code, which contains the following:

cd ~/Documents/Code

However, when I run it by simply executing

$ code

Nothing happens. Why is this, and how can I make code perform as I would like?

Upvotes: 1

Views: 594

Answers (2)

Vytenis Bivainis
Vytenis Bivainis

Reputation: 2376

If that file is in /usr/bin because it's on the PATH and executable, you can run it in your current shell with . $(which code) or source $(which code), but there are better ways to cd, one is mentioned by Jonathon.

Upvotes: 1

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137517

When you run code, a new process is spawned to execute that script. The script changes directories (for his process) and returns. Your original shell's process still has the same working directory. Child processes cannot manipulate the state of their parent.

A better way to accomplish this would be with an alias. Add this to your ~/.bashrc:

alias code='cd ~/Documents/Code'

Upvotes: 4

Related Questions