Mahdy Zguem
Mahdy Zguem

Reputation: 11

Why do I get an error when I use 'source' to run a TCL script?

I am working on TCL scripts right now. When I run tclsh script.tcl the script works perfectly but when I run source script.tcl the commands are no longer found.

#!/usr/bin/env tclsh
proc test {} {
  set a 43
  set b 27
  set c [expr $a + $b]
  set d [expr [expr $a - $b]* $c]
  for {set k 0} {$k < 10} {incr k} {
    if {$k < 5} {
      puts "k<5, pow=[expr pow($d,$k)]"
    } else {
      puts "k>=5, mod=[expr $d % $k]"
    }
  }
}

...which, when run, causes the error:

$ source myfirst.tcl

Command 'proc, not found, did you mean:

  command 'croc' from snap croc (6.4.10)
  command 'prof' from deb profphd
  command 'nproc' from deb coreutils
  command 'proj' from deb proj-bin

See 'snap info <snapname>' for additional versions.

bash: myfirst.tcl: line 7: syntax error near undexpected token `k'

Upvotes: 0

Views: 2334

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137577

Tcl code is run by a Tcl interpreter (usually tclsh or wish, but many applications embed Tcl too). Bash code is run by a bash interpreter. The two languages have only extremely superficial similarities; the source command is one of those, but proc is a Tcl-only command (bash has function instead for that sort of thing).

This means that whatever runs that source command needs to also understand what the target file is written in.

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295443

source cannot be used to run any script that is not written in the native language of the shell you're invoking it in.

That is, in bash, source can only be used to run bash scripts. It cannot run TCL scripts. This is by its nature: What source does is skip running an extra shell or other interpreter (thus, forcing your #!/usr/bin/env tclsh shebang to be ignored), and run the code in the shell you're already in.

If that shell cannot natively parse the language that the script you're sourcing is written in, syntax errors are to be expected -- content written in one language is being parsed by an interpreter designed exclusively to support a different one. The bash: prefix on your error message makes it clear that this is the case in practice; it's bash, not tclsh, trying to interpret the script.

Upvotes: 2

Related Questions