csh/C shell scripts: if statement syntax

Conditional expressions give programs life. The ability to branch makes shell scripts powerful. This recipe shows the basic if then else structure for csh, the C shell.


Basic if statement syntax:

if (condition) then
commands
endif

The addition of one or more else keywords offers additional flexibility:

if (condition) then
commands
else if (other condition) then
commands
else
commands
endif

The Conversation

Follow the reactions below and share your own thoughts.

6 Responses to “csh/C shell scripts: if statement syntax”

  1. November 07, 2008 at 6:08 pm, Dan said:

    test for the existence of a variable using
    if ($?LD_LIBRARY_PATH == 0) then
    setenv LD_LIBRARY_PATH /usr/lib;
    endif

    Reply

    • March 11, 2009 at 8:53 pm, Dan said:

      A variation of the above would be:

      if ( ! ${?LD_LIBRARY_PATH} ) then
      setenv LD_LIBRARY_PATH /usr/lib
      endif

      Use the {} around variables as a habit since the variable names can often interfere with shell syntax.

      The semicolon at the end is ignored.

      Reply

  2. March 11, 2009 at 8:51 pm, Dan said:

    Without concrete examples of how the syntax is actually used, this is almost useless information.

    Reply

    • December 14, 2009 at 3:23 pm, Paul said:

      Almost? More like completely…

      Reply

  3. March 23, 2011 at 3:50 pm, Chisimobi said:

    need more examples

    Reply

  4. March 23, 2011 at 3:50 pm, Chisim_obi said:

    need more examples

    Reply

Leave a Reply