shell脚本中if的语法不同

时间:2013-06-21 17:49:46

标签: bash shell csh tcsh

我正在学习shell脚本,我找到了shell脚本条件语句的不同语法。 csh脚本是否具有与tcsh脚本不同的语法。有人说

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

一些使用

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

我尝试了自己,我得到的错误如“if:Empty if”或“If:Expression Syntax”和这些消息非常简短易懂。所以我想问一下如何解决这些问题,是否有基于shell的解决方案(csh,tcsh)

如果我的shell是tcsh,我应该总是tcsh脚本还是我可以编写bash脚本。

2 个答案:

答案 0 :(得分:4)

cshtcsh共享if语句的相同语法:

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

你的另一个例子(可能)来自shbash

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

您的列表恰好是对程序的调用(有时是内置的shell)[

只要你输入正确的

,你就可以为任何你想要的shell编写脚本
#!/bin/sh
#!/bin/bash
#!/bin/csh
#!/bin/tcsh

将您脚本的目标shell与文件顶部相匹配。

答案 1 :(得分:0)

这是实际的脚本 -

#!/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
相关问题