Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a bash script from a tcl script and returning and exit status

Tags:

bash

tcl

I am attempting to call a bash script from a TCL script and need to get exit status from the bash script or at least pass something back into the TCL script so that I can tell if my script executed successfully. Any suggestions?

like image 257
tgai Avatar asked Aug 24 '11 14:08

tgai


People also ask

How do I run a TCL script in a shell script?

You can run this program by starting tclsh from the start menu, then typing the command source c:/hello. tcl. Note that the traditional Windows \ is replaced with /. to your script.

How do I exit a bash script?

One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.

Do you need to exit a bash script?

Often when writing Bash scripts, you will need to terminate the script when a certain condition is met or to take action based on the exit code of a command.


3 Answers

See http://wiki.tcl.tk/exec -- click the "Show discussion" button -- there's a very detailed example of how to do exactly what you're asking. What you need though is catch

set status [catch {exec script.bash} output]

if {$status == 0} {
    puts "script exited normally (exit status 0) and wrote nothing to stderr"
} elseif {$::errorCode eq "NONE"} {
    puts "script exited normally (exit status 0) but wrote something to stderr which is in $output"
} elseif {[lindex $::errorCode 0] eq "CHILDSTATUS"} {
    puts "script exited with status [lindex $::errorCode end]."
} else ...
like image 134
glenn jackman Avatar answered Oct 16 '22 16:10

glenn jackman


What you want is exec the result of which will be in the return value, be warned however there are lots of gotchas using exec, particularly if you need to do any complex quoting

like image 21
jk. Avatar answered Oct 16 '22 16:10

jk.


My experience in tcl is limited to occasional dabbling. However, following links starting with the one in @jk's answer led me to this page which discusses the errorCode variable and related things that might be useful this circumstance. Here's a quick example demonstrating the use of errorCode:

tcl:

set ret_val [catch { exec /bin/bash /path/to/bash_script }]
set errc $errorCode
set ret_val [lindex [split $errc " " ] 2]
puts $ret_val

bash_script, as referenced above:

#!/bin/bash
exit 42

which led to output of:

42

like image 1
GreenMatt Avatar answered Oct 16 '22 14:10

GreenMatt