1

Say I have a script that is always run from an interactive shell. I would like this script to launch an interactive subshell that is a replica of the parent (i.e., all environment variables, etc. preserved) and then run arbitrary commands (specifically, I would like to amend PS1 and define a few aliases). I need a genuine subshell (rather than using source, otherwise environment variables won't persist after the script has finished) and it needs to be shell agnostic (i.e., works with bash, zsh, etc.)

The only way I've been able to accomplish this, so far, is to launch and script the shell with expect. This is a bit horrible, but it sort-of-works:

expect <(cat <<-EXPECT
  spawn $SHELL
  send "export FOO=\"$foo\"\r"
  send "PS1=\"(foo:$FOO) \\\$PS1\"\r"
  send "alias foo=\"do_somthing --foo=$FOO\"\r"
  send "clear\r"
  interact
EXPECT)

Is there a better way? (I also notice that this approach appears to introduce a problem with the screen redrawing and character encoding.)

The problem with doing something like PS1="$foo" $SHELL is that PS1 can be overridden by the shell's global and user .rc files. There doesn't seem to be a shell agnostic way of providing a custom .rc file.

Your Answer

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

Browse other questions tagged or ask your own question.