1

I am learning shell script and I find different syntax for shell script conditional statements. Does csh script have a different syntax than tcsh script. Some say

 if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
echo "You have access!"
 else
echo "ACCESS DENIED!"
  fi

some use

 if ($PASSWORD == $VALID_PASSWORD)
 echo "You have access!"
 else
echo "ACCESS DENIED!"
 endif

I tried my own and I get errors like "if: Empty if" or "If: Expression Syntax" and these messages are very brief to understand. So I thought of asking how to sort out these issues and are there solutions different based on shell (csh, tcsh)

If my shell is tcsh, should I always tcsh script or can I write bash script.

2
  • 1
    As Carl's answer says, you can write scripts using whatever shell you like, regardless of what shell you use interactively. But read this: perl.com/doc/FMTEYEWTK/versus/csh.whynot Commented Jun 21, 2013 at 22:00
  • Thanks Thompson .. I am just learning to program shells and I can learn bash shell than csh shell scripting Commented Jun 21, 2013 at 22:21

2 Answers 2

4

csh and tcsh share the same syntax for an if statement:

if (expr) then
...
else if (expr2) then
...
else
...
endif

Your other example is (probably) from sh or bash:

if list; then list; [ elif list; then list; ] ... [ else list; ] fi

Where your list happens to be an invocation of the program (or sometimes shell builtin) [.

You can write scripts for whatever shell you want as long as you put the right one of

#!/bin/sh
#!/bin/bash
#!/bin/csh
#!/bin/tcsh

to match your script's intended shell at the top of the file.

Sign up to request clarification or add additional context in comments.

4 Comments

The error I got for following code is "if : Empty if" if ( $1 == "one") echo "one" else if ($1 == "two") echo "two" else echo " no proper input" endif when executed as ./script one
@Raghav that's because your if statement is missing its then keyword.
Thanks Gordon .. I did not know if and then should be in same line.. Now code is working
csh and tcsh also permit a limited single-line if statement: if (expr) stmt (distinguished by the lack of a then) -- but that form doesn't permit an else.
0

This is the actual script for that -

#!/bin/sh
# This is some secure program that uses security.

VALID_PASSWORD="secret" #this is our password.

echo "Please enter the password:"
read PASSWORD

if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
    echo "You have access!"
else
    echo "ACCESS DENIED!"
fi

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.