0

I have a shell-function that executes a command within a sub-shell, after setting some environment variables, e.g.

$ with-env-overrides git status

It's implemented using eval in a sub-shell

with-env-overrides() {
  (
    source $HOME/.env-overrides
    eval "$@"
  )
}

this means I can make use of aliases, and shell-functions, e.g.

$ with-env-overrides gs    

but unfortunately, eval gets confused when arguments contain spaces, or shell meta-characters, e.g.

$ with-env-overrides grep "foo bar" /etc/passwd
grep: bar: No such file or directory

How can I achieve this without using eval, but without loosing the ability to use aliases etc?

1 Answer 1

2

You can do the same but without eval.

with-env-overrides() {
  (
    source $HOME/.env-overrides
    "$@"
  )
}

Example:

$ cat ~/.env-overrides 
export A=1000
$ export | grep ^A=
$ with-env-overrides export | ^grep A=
declare -x A="1000"

As you can see, in the second case, you've got an environment with the A variable.

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

3 Comments

Exactly what I would suggest.
Hmm, unfortunately, I don't appear to be able to leverage aliases using that method.
@MikeWilliams: That's correct. Aliases are very limited, and have a number of wierdnesses. One of them is that they act more like built-ins than commands, so you cannot quote them or construct them out of two strings, or expand a parameter to invoke one. Use shell functions instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.