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.

  • This looks like reinventing the wheel. What you describe is the exact purpose of the init file. – Wildcard Oct 21 '16 at 3:00
  • What's the point of not using the --init-file option? – Tomasz Oct 21 '16 at 7:15
  • 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 Oct 21 '16 at 7:36

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
  • After more thought this seems fine for what I'm doing. I can pass environment variables as arguments to the init file. Thanks! – peskal Oct 21 '16 at 7:37

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.