2

I am writing a bash function that will run some commands to setup the environment and then leave the user at the prompt.

I can run

bash -c 'ls'

To execute ls in bash.

I can also do

bash -c 'ls ; exec bash'

To execute ls, and then leave a bash prompt open.

However, I want to source a file and setup some aliases, functions, and environment variables and then leave the prompt open, so something like this:

 bash -c 'source env.sh ; exec bash'

Of course, this doesn't work because subshells will not inherit aliases or functions. Is there a way around this problem? I'd prefer to still have the user's .bashrc be sourced, and not use the --init-file option.

3
  • 1
    This looks like reinventing the wheel. What you describe is the exact purpose of the init file.
    – Wildcard
    Commented Oct 21, 2016 at 3:00
  • 1
    What's the point of not using the --init-file option?
    – user147505
    Commented Oct 21, 2016 at 7:15
  • 1
    Hmm, it was moreso that I wanted to avoid cluttering my computer with init files. I was writing some helper functions to initialized my Android setup (which requires switching my shell to bash and sourcing some files). Making a new file seemed excessive when I only needed to execute around 5 lines
    – peskal
    Commented Oct 21, 2016 at 7:36

1 Answer 1

3

Set up an init file that will source the user's init file at the start, and then do whatever else you want:

$ cat env.sh
. ~/.bashrc
export SOMEVAR="value"
somespecialfunction() {
  printf '%s\n' "I'm so cool"
}
$ bash --init-file env.sh
1
  • 1
    After more thought this seems fine for what I'm doing. I can pass environment variables as arguments to the init file. Thanks!
    – peskal
    Commented Oct 21, 2016 at 7:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .