JLB JLB - 1 month ago 9
Bash Question

How to dynamically compute value of a variable and use it in a command?

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).

Answer

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"'