0

I am trying to create a file that I can run from the command line:

.bashrc

export gorepo="cd /home/pol/dcu/practicum/gitrep"

and also

alias gorepo="/home/pol/dcu/practicum/gitrep"

Then in an executable file on $PATH

#!/bin/bash
gorepo # gorepo is defined in .bashrc
git checkout

I've tried various combinations of export, alias and using shell variables and bash functions to no avail - I'm at my wit's end!

How do I create a command that will simply cd into my repo and then run git checkout and return me to the shell in the repo directory?

2

This declares a variable called gorepo containing the literal text cd /home/pol/dcu/practicum/gitrep:

export gorepo="cd /home/pol/dcu/practicum/gitrep"

This declares a command (alias) called gorepo that runs the program /home/pol/dcu/practicum/gitrep:

alias gorepo="/home/pol/dcu/practicum/gitrep"

This tries to use an alias that isn't defined the context of the shell script:

#!/bin/bash
gorepo # gorepo is defined in .bashrc
git checkout

What I think you want is either this program, which will change directory for the duration of the script and check out your code:

#!/bin/bash
cd /home/pol/dcu/practicum/gitrep
git checkout

Or this alias (suitable for .bashrc), which will change directory in the current shell's context, and then check out your code:

alias gorepo='cd /home/pol/dcu/practicum/gitrep && git checkout'
| improve this answer | |
  • Deadly - that last one is just what I want - it changes the directory, does the checkout and LEAVES YOU IN THE DIRECTORY!. Great stuff - thanks! – Vérace Oct 3 '18 at 15:00
0

What cd does is: change the working directory of the current shell. When you start a script another shell (process) is started to execute the script. That shell process succesfully changes working directory when cd executes, but when the script ends your back in the previous shell where you started the script from.

Ways around this are:

1) run your script by "sourcing", with either:

bash$ source yourscript

or (exactly the same):

bash$ . yourscript

This will run the script in the current shell, so cd will change directory for that process and thus remain in effect after the script ends.

2) Define an alias. An aliased command will also executed in the current shell process. See roaima's answer how to do this.

| improve this answer | |
0

I don't know if this is what you really want or if you think this is the best solution for what you intend to do.

git has the -C <repopath> <command> <branch>

In tour case

git -C /home/pol/dcu/practicum/gitrep checkout master`

This will not return you inside of the desired directory, but maybe it will help.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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