Search code examples
tclcshtcsh

Is there is a way of sourcing csh file in tcl script and bringing variables to the main shell?


I'm trying to source a some.cshrc during TCL script execution. I get no error but the variables set in some.cshrc are not passed back to the shell.

When writing it like: source some.cshrc I'm getting an error. Then I tried: exec /bin/csh -c "source some.cshrc"

Please advise


Solution

  • Since Csh and Tcl are two completely different languages, you cannot simply load a Csh file in a Tcl script via a source command.

    You can think of a workaround instead. Let us assume you want to load all the variables set with a setenv command. Example contents of some.cshrc file could look something like this:

    setenv EDITOR vim
    setenv TIME_STYLE long-iso
    setenv TZ /usr/share/zoneinfo/Europe/Warsaw
    

    You can write a Tcl script which reads this file line by line and searches for setenv commands. You can then reinterpret the line as a list and set an appropriate variable in a global namespace via an upvar command.

    #!/usr/bin/tclsh
    
    proc load_cshrc {file_name} {
      set f [open $file_name r]
      while {[gets $f l] >= 0} {
        if {[llength $l] == 3 && [lindex $l 0] eq "setenv"} {
          upvar [lindex $l 1] [lindex $l 1]
          set [lindex $l 1] [lindex $l 2]
        }
      }
      close $f
    }
    
    load_cshrc "some.cshrc"
    puts "EDITOR = $EDITOR"
    puts "TIME_STYLE = $TIME_STYLE"
    puts "TZ = $TZ"
    

    Please note, that since we do not run a Csh subshell any variable substitutions in the Csh script would not occur.