Pass variable from awk to bash
How can I pass variable from awk to bash? I want to pass a lot of variable, so I don't use:
x=$(awk '.....)I thing it's not usefull.
2 Answers
Assuming you trust the incoming data that awk is processing.
You can have awk print out shell variable declarations, and source the output of awk like it's a shell file:
source <( awk ' # .... print "var1=" value1 print "var2=" value2 # .... ' input
)
echo "shell var1 = $var1"
echo "shell var2 = $var2" 3 This is a general problem that has appeared in many variants on StackExchange already, e.g.
The answer is always that it is not possible for a process to change the environment of its parent (and that's what you're trying to achieve when you would ask awk to set an environment variable in the shell that spawned it).
The solution recommended usually is to source the output, as Glenn has shown. You have to trust the program, though. You're basically executing arbitrary code.
Another, slightly different, solution would be to output the var=value lines to a named file and source that file, instead. (Sourcing basically executes the contents of a file in the current shell, as if you had typed them; see .) An advantage of this approach is that you can check the contents of this file before sourcing it.