1

I have this script:

#!/bin/bash

cd ~/my-dir && bash && runall

And I added this script to my $PATH and when I run this script it does 2 things first.

  1. It changes the current directory and execute bash so that my shell also changes the current dir and i can work there.
  2. Run runall (another shell script) in this folder.

Actual Result:

Script changes my current shell directory successfully. However, runall is not executed.

Expected Result:

Script changes current shell directory of mine to the my-dir and then execute runall

How can I solve this?

Note:

I know that i can do this:

cd some-dir/ && runall

But this will not change my current session to that dir. I also want to change my current shell directory.

Reason:

I want to also change my current working directory so that i can run other manual commands there after runall executed.

Dennis
  • 1,805
  • 3
  • 22
  • 41
  • 2
    This doesn't change your "current session" at all. It's starting a new shell, not modifying the state of your existing one. If you exit that new shell, `runall` will run and then you'll be back in your old one. – Charles Duffy Dec 30 '20 at 16:09
  • 3
    If you want to modify your existing session, a script is the wrong tool entirely -- use a function instead. – Charles Duffy Dec 30 '20 at 16:11

1 Answers1

4

This is very nearly a duplicate of Change the current directory from a Bash script, and the answer is very similar -- the only difference being the appending of the command you want to run.

Don't use a script at all; instead, in your ~/.bashrc or similar, define a function:

runInMyDir() {
  cd ~/my-dir || return
  runall
}

...to define a command runInMyDir. (If you want runall to happen in the background, add a & at the end of that line).


If you do want a script, that script needs to be sourced rather than executed out-of-process -- when a program is executed as an executable external to the shell, it has already been split off from the original shell before it starts, so it has no opportunity to change that shell's behavior. Thus, if you created a file named runInMyDir with the commands cd ~/my-dir || return and runall, you would need to run source runInMyDir rather than just runInMyDir to invoke it.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Thank you for pointing me to the right direction. It did worked very well. Thanks! I removed script and moved to a function as you said. – Dennis Dec 30 '20 at 18:00