Search code examples
csh

variable is not modified in if statement CSH


I have the following very simple code:

#!/usr/bin/env csh

set status=0
if ( 0 == 0 ) then
    ls ./dummyDir
    set status=$?
    echo $status
endif
echo $status

And the problem is that the last echo of $status is 0 while the first one is set to exit code which is 2? Why is this happening? Why status is not modified inside if statement. The same equivalent of this in bash is perfectly working.


Solution

  • $status is an alias for $?; so it gets overwritten by the echo. You'll need to use a different variable name:

    set ls_status = 0
    if ( 0 == 0 ) then
        ls ./dummyDir
        set ls_status = $?
        echo $ls_status
    endif
    echo $ls_status
    

    Outputs:

    ls: cannot access './dummyDir': No such file or directory
    2
    2