Issue
How can I make the below code work? I want to pass custom_var
value to the command
script.
$ command="echo $custom_var"
$ custom_var=myValue nohup $command > log.txt && cat log.txt
$ # WRONG. Should be 'myValue'
This doesn't seems to work. The above output should print "myValue". Also tried:
$ command="echo \$custom_var"
$ custom_var=myValue nohup $command > log.txt && cat log.txt
$ $custom_var # WRONG. Should be 'myValue'
Thank you
Solution
You've made two mistakes. First one is this syntax
var=val some_command
creates a temporary exported variable visible only to some_command
. It will not exist after that statement completes. So your subsequent use of custom_var
will have whatever value, if any, it had before that statement was run.
Second mistake is you don't understand how POSIX 1003 shells do variable expansion nor how env vars differ from non-env vars. The custom_var
is passed to "the command
script." The problem is your attempt to verify that requires the parent shell, the one in which you're running these commands, to do the variable expansion. Try this instead. Create a file named /tmp/cvar with this content:
echo custom_var is $custom_var
env | grep custom_var
Then type
custom_var=myValue sh /tmp/cvar
Answered By - Kurtis Rader Answer Checked By - Mildred Charles (WPSolving Admin)