Assigning system command's output to variable

前端 未结 6 1203
梦毁少年i
梦毁少年i 2020-11-28 04:55

I want to run the system command in an awk script and get its output stored in a variable. I\'ve been trying to do this, but the command\'s output always goes t

6条回答
  •  再見小時候
    2020-11-28 05:40

    To run a system command in awk you can either use system() or cmd | getline.

    I prefer cmd | getline because it allows you to catch the value into a variable:

    $ awk 'BEGIN {"date" |  getline mydate; close("date"); print "returns", mydate}'
    returns Thu Jul 28 10:16:55 CEST 2016
    

    More generally, you can set the command into a variable:

    awk 'BEGIN {
           cmd = "date -j -f %s"
           cmd | getline mydate
           close(cmd)
         }'
    

    Note it is important to use close() to prevent getting a "makes too many open files" error if you have multiple results (thanks mateuscb for pointing this out in comments).


    Using system(), the command output is printed automatically and the value you can catch is its return code:

    $ awk 'BEGIN {d=system("date"); print "returns", d}'
    Thu Jul 28 10:16:12 CEST 2016
    returns 0
    $ awk 'BEGIN {d=system("ls -l asdfasdfasd"); print "returns", d}'
    ls: cannot access asdfasdfasd: No such file or directory
    returns 2
    

提交回复
热议问题