TCL Checking Environment Variables

11.7k views Asked by At

So I have been trying to find an answer for this for a bit and could not find the answer on the internet. I need to check to see if an environment variable exists. I thought I had the right code but it keeps returning false.

if { [info exists ::env(USER)] } {
    RAT::LogMsg INFO "Found USER"
} else {
    RAT::LogMsg INFO "Nope!"
}

Any ideas?

2

There are 2 answers

0
Donal Fellows On

You might want to check what environment variables are actually set; I don't think that USER is one of the guaranteed ones.

RAT::LogMsg INFO "Got these env-vars: [lsort [array names ::env]]"

If puts stdout works in your environment, you can try doing:

parray ::env

(The parray command is a procedure that pretty-prints an array.)


To get the current username reliably, check out the tcl_platform array's user element. That array is generated internally by Tcl (well, with probes to relevant basic OS APIs) instead of by looking at environment variables, and that particular element is always present back at least as far as Tcl 8.4.

RAT::LogMsg INFO "Username is $::tcl_platform(user)"

I've just noticed that the documentation is wrong: it says that the user element comes from USER and/or LOGNAME environment variables. It doesn't, and doesn't in at least 8.5 and 8.6. (And it's definitely my mistake. I forgot to update the code when I fixed this. Ooops!)

0
Str. On

You have the right code, test in tclsh:

% if {[info exists ::env(USER)]} {puts "found $::env(USER)"}
found strobel
% 

The problem must be in your environment.