Zsh alternative to bash's quick assignment and inheritance trick

1

There's a trick available in bash allowing you to set environment variable for child process and run it in single line, retaining original values of variable in the shell. For example, in order to set the "LANG" and "FOO" environment variables and then run "gedit", we would use the following command (from Ubuntu docs):

LANG=he_IL.UTF-8 FOO=bar gedit

It doesn't work in zsh.

Is there a similarly simple alternative?

Michael Pankov

Posted 2013-02-11T15:03:25.377

Reputation: 113

Answers

2

What you describe works the same in Zsh as it does in Bash. From the manual:

A simple command is a sequence of optional parameter assignments followed by blank-separated words, with optional redirections interspersed. The first word is the command to be executed, and the remaining words, if any, are arguments to the command.

If a command name is given, the parameter assignments modify the environment of the command when it is executed. (…)

… and in Bash:

When a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right.

  1. The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later processing.

If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment

slhck

Posted 2013-02-11T15:03:25.377

Reputation: 182 472

I was testing it with TEST=5 echo $TEST, but I've now discovered that it doesn't work neither in zsh nor in bash (outputs nothing). In zsh, echo is builtin and it may explain why it doesn't work; however, what's wrong in case of bash? – Michael Pankov – 2013-02-11T16:37:08.670

1I see. Read the Bash manual again: "words that the parser has marked as variable assignments (those preceding the command name) […] are saved for later processing – your echo command won't see the change of $TEST. Run TEST=5 sh -c 'echo $TEST' and see what happens! – slhck – 2013-02-11T18:51:33.897