Tcl: Multiple Conditionals Inside the If Statement

Just trying to do some basic check in a script... to produce an error if $argc is not either 1 or 2.

I tried:

if { ( $argc != 1 ) || ( $argc != 2 ) } {
        puts "ERROR: \$argc should be either 1 or 2.\n"; exit 1
}

and

if { ( $argc != 1 || $argc != 2 ) } {
        puts "ERROR: \$argc should be either 1 or 2.\n"; exit 1
}

etc.

but couldn't make it work using any of the parenthesis/brace combinations.

Any help would be greatly appreciated.

1

2 Answers

This is basic logic.

Your example won't work because 2 is not equal to 1 so the first test is true.

To negate an OR conjunction, you negate each test and change the OR to an AND. You want this state:

if { ( $argc == 1 ) || ( $argc == 2 ) } {
  puts "ok"
} else {
  puts "ng"
}

So use:

if { ( $argc != 1 ) && ( $argc != 2 ) } {
  # i.e. if $argc is either anything other than a 1 or a 2...
  puts "ERROR: \$argc should be either 1 or 2.\n"; exit 1
}
1

Another way:

if {$argc ni {1 2}} { ... }

That is: if the value of argc is not in the list containing 1 and 2, ...

The ni operator requires Tcl 8.5 or later.

Documentation: if, ni (operator)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest