Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning system command's output to variable

Tags:

pipe

awk

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 to the shell and I'm not able to capture it. Any ideas on how this can be done?

Example:

$ date | awk --field-separator=! {$1 = system("strip $1"); /*more processing*/} 

Should call the strip system command and instead of sending the output to the shell, should assign the output back to $1 for more processing. Rignt now, it's sending output to shell and assigning the command's retcode to $1.

like image 416
Sahas Avatar asked Dec 25 '09 09:12

Sahas


People also ask

How do you set a value to a variable in Linux?

A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data. A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.


2 Answers

Note: Coprocess is GNU awk specific. Anyway another alternative is using getline

cmd = "strip "$1 while ( ( cmd | getline result ) > 0 ) {   print  result }  close(cmd) 

Calling close(cmd) will prevent awk to throw this error after a number of calls :

fatal: cannot open pipe `…' (Too many open files)

like image 176
ghostdog74 Avatar answered Oct 06 '22 00:10

ghostdog74


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 
like image 33
fedorqui 'SO stop harming' Avatar answered Oct 06 '22 01:10

fedorqui 'SO stop harming'