0

Reducing what I'm trying to do to a simple example:

env temp=`pwd` echo "$temp"

I get this message:

temp: Undefined variable.

How do I make it work (in a shell-agnostic way)? I'm expecting the result of pwd to be printed.

My actual requirement uses a complicated expression in place of pwd, a script in place of "echo", and the variable $temp as an argument to that script.

Also, I want to set this variable only for this single command, and not for the whole shell (or any subsequent subshells).

JLB
  • 3
  • 2
  • Why do you need this? The shell expands `$temp` before the command is run, so the contents of the environment are irrelevant. – chepner Oct 24 '16 at 23:33
  • @jonathan-leffler I think this is a dupe of the `bash` part, but not of the `csh` part. – davejagoda Oct 25 '16 at 00:05
  • The correct answer to the `csh` part is "Don't use the sea-shell; leave sea-shells on the sea-shore (where, with any luck, the tide will wash them away)". It is not clear why the code tries to pass `temp` as both an argument and an environment variable. If it's a complicated command instead of `pwd` and script instead of `echo`, the whole thing should be wrapped up in a script, and the script should be a Bourne/Korn/POSIX/Bash shell script and not a C shell script. – Jonathan Leffler Oct 25 '16 at 00:10
  • This came to mind: http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/ but I assumed there was a good reason to require `csh` in the original question. – davejagoda Oct 25 '16 at 00:36
  • @chepner, Ah, I didn't know the sequence in which bash expand variables - that explains it. Thanks. – JLB Oct 25 '16 at 21:20
  • @JonathanLeffler I am aware of the pitfalls with C shell scripting (still, thanks for the reminder). I just wanted a portable solution since its users use all kinds of interactive shells. Perhaps it's best to write a wrapper script than a super complicated one-liner. Thanks. – JLB Oct 25 '16 at 21:25

1 Answers1

0

How about something like this for sh and bash

(export temp=`pwd`; echo $temp)

And this for csh

csh -c 'setenv temp `pwd`; echo "$temp"'
davejagoda
  • 2,420
  • 1
  • 20
  • 27