Question

I'm trying to create a script that launches another script and have it as a child directly. My goals are:

  • the child program should see a different $HOME
  • the child script should run in a different directory than the current working directory (i.e. different pwd)
  • no extra shells

I achieved the first two goals via subshells and exec, but I've yet to manage the third one. Could someone help me?

Here are the details. For ease of description, I will call the first script run, and the other program sleepcmd. Here's the content of sleepcmd script

echo $HOME && exec sleep 1000

Here's the content of run script

(HOME=~/foo/bar && cd $HOME/bin && ./sleepcmd)

Adding an exec before ./sleepcmd invocation, i.e.

(HOME=~/foo/bar && cd $HOME/bin && exec ./sleepcmd)

gets this to just one extra shell, compared with running sleepcmd (or sleep) directly.

How can I do better than that, and get rid of the () subshell, while still invoking sleep 1000 with a different $HOME and working directory?

Was it helpful?

Solution

try

pushd
VAR=value command [args...]
popd

e.g.

pushd ~/foo/bar/bin
HOME=~/foo/bar ./sleepcmd
popd

OTHER TIPS

You could try using the "source" command on a file (e.g. "myscript") containing the new environment and commands, e.g.

source myscript

or

. myscript

and set up the new environment at the top of myscript. However, you will have to set the environment back to what it was before at the end of myscript, or it will continue in your main script.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top