Search code examples
tcsh

In tcsh how do you get the exit status of a command in backquotes?


I have the following code in my tcsh startup script:

set _color_count = `sh -c "tput -T${TERM}-256color colors 2>/dev/null"`
if ($? == 0) then  # check if it was a valid terminal type
    if ($_color_count != 256) then  # sanity-check
        echo "Warning: Color count '$_color_count' for '${TERM}-256color' is not 256"
    endif
    setenv TERM "${TERM}-256color"
endif

My problem is that the exit status ($?) is always zero, even when the tput command returns a non-zero exit status due to an invalid terminal type. If I don't capture the output of the command, checking the exit status works fine:

sh -c "tput -T${TERM}-256color colors 2>/dev/null"

How do I determine whether or not the tput command returned a non-zero exit status, given it's in backquotes?


Solution

  • It turns out that this was a behavioral change introduced in tcsh version 6.17.05 (see original bug report). It looks like it will be reverted as of tcsh version 6.18.00 (see regression bug report), but it has obviously made it into the wild.

    For affected versions, though, you can set the variable $anyerror before running the command in backquotes:

    set anyerror
    set _color_count = `sh -c "tput -T${TERM}-256color colors 2>/dev/null"`
    

    According to my tcsh man page for special shell variable status:

    status The status returned by the last command, unless the variable anyerror is set, and any error in a pipeline or a backquote expansion will be propagated (this was the default csh behavior).