Re: How to execute shell command and store result to variable?
Posted in 1997
On Fri, 21 Mar 97 13:29:06 GMT, ehlim@resorts.po.my (EHLIM) said: > > Can I run a Unix shell command like " ls .... | wc -l " and store the result > into a variable for my program varification purpose. For this and regular file access I recommend C wrappers which return C FILE pointers as integers. This isn't strictly portable but it works on all the machines I use (or am likely to). The popen(3) component is just int c_popen(int argc) { char *cmd, *mode; FILE *fp; CHECK_ARGC(c_popen, 2); mode = proper_popquote(NULL, 0); cmd = proper_popquote(NULL, 0); fp = popen(cmd, mode); xfree(cmd); xfree(mode); retint((int)fp); return 1; } the pclose(), fgets() and so on are analogous. Usage is like from C, not feature rich but functional. As an example here's a program which processes a fortune. main define s char(1023), fhp int, i int let fhp = c_popen('fortune', 'r') if not fhp then let s = "Can't fork: ", c_strerror(c_errno_get()) call stderr_puts(s clipped) exit program 1 end if while 1 let s = c_fgets(fhp) if s is null then exit while end if -- chop newline let i = length(s) case when i = 0 when s[i] != ascii 10 when i = 1 let s = "" otherwise let i = i - 1 let s = s[1,i] end case display 'read: ', s clipped end while let i = c_pclose(fhp) case when i = 0 -- Success. when i = -1 let s = 'pclose() error: ', c_strerror(c_errno_get()) call stderr_puts(s clipped) exit program 1 otherwise let s = 'return status ', leftjust(i), ' from fortune' call stderr_puts(s clipped) exit program 1 end case end main -- Roderick Schertler roderick@argon.org