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.

2
  • 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. Commented Dec 30, 2020 at 16:09
  • 3
    If you want to modify your existing session, a script is the wrong tool entirely -- use a function instead. Commented Dec 30, 2020 at 16:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.