user3304467
user3304467

Reputation: 81

Execute linux command in tcl

When I execute the command openssl rand -base64 12 in the terminal it prints the output:

mFpVuBreI0dPENLF

I have the following tcl script where I have used exec to call to linux:

for {set kb 0} {$kb<5} {incr kb} {
    exec openssl rand -base64 12 
    puts "end"
}

When I run the above script it prints the word "end" four times but doesn't print the output of openssl rand -base64 12. What is the reason for this?

Can any one help me?

Upvotes: 2

Views: 4360

Answers (1)

patthoyts
patthoyts

Reputation: 33193

Capture the output of the executed subprocess and print that. eg:

for {set n 0} {$n < 4} {incr n} {
  set r [exec openssl rand -base64 12]
  puts [format {%d %s} $n $r]
}

Testing this:

$ tclsh8.5 z.tcl
0 GG6ppnaPgJoTPxlC
1 xLHDiDBBQ6cxxvmg
2 wGnqqegconlwu3YV
3 QRM0IsXzw4rk3r+j

The reason is that the standard output of the subprocess has been captured as documented:

If standard output has not been redirected then the exec command returns the standard output from the last command in the pipeline

so stdout of openssl is no longer connected to the terminal. Instead Tcl reads it and places anything written into a variable unless you use one of the redirection options given in the manual page. For processes that produce a lot of output using open can be a better option as you can then read the output in pieces but for this example exec is fine.

Upvotes: 4

Related Questions