Set variable in current shell from awk

后端 未结 7 1922
花落未央
花落未央 2020-12-29 05:40

Is there a way to set a variable in my current shell from within awk?

I\'d like to do some processing on a file and print out some data; since I\'ll rea

7条回答
  •  攒了一身酷
    2020-12-29 06:01

    Make awk print out the assignment statement:

    MYVAR=NewValue
    

    Then in your shell script, eval the output of your awk script:

    eval $(awk ....)
    # then use $MYVAR
    

    EDIT: people recommend using declare instead of eval, to be slightly less error-prone if something other than the assignment is printed by the inner script. It's bash-only, but it's okay when the shell is bash and the script has #!/bin/bash, correctly stating this dependency.

    The eval $(...) variant is widely used, with existing programs generating output suitable for eval but not for declare (lesspipe is an example); that's why it's important to understand it, and the bash-only variant is "too localized".

提交回复
热议问题