Raghav
Raghav

Reputation: 796

Different syntax for if in shell script

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.

Upvotes: 1

Views: 6357

Answers (2)

Akshay
Akshay

Reputation: 1

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

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224944

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.

Upvotes: 4

Related Questions