Set variable in current shell from awk

后端 未结 7 1891
花落未央
花落未央 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:08

    To synthesize everything here so far I'll share what I find is useful to set a shell environment variable from a script that reads a one-line file using awk. Obviously a /pattern/ could be used instead of NR==1 to find the needed variable.

    # export a variable from a script (such as in a .dotfile)
    declare $( awk 'NR==1 {tmp=$1} END {print "SHELL_VAR=" tmp}' /path/to/file )
    export SHELL_VAR
    

    This will avoid a massive output of variables if a declare command is issued with no argument, as well as the security risks of a blind eval.

提交回复
热议问题