【问题标题】:Different syntax for if in shell scriptshell脚本中if的不同语法
【发布时间】:2013-06-21 17:49:46
【问题描述】:

我正在学习 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 脚本。

【问题讨论】:

  • 正如卡尔的回答所说,您可以使用您喜欢的任何 shell 编写脚本,而不管您以交互方式使用什么 shell。但请阅读:perl.com/doc/FMTEYEWTK/versus/csh.whynot
  • 谢谢 Thompson .. 我只是在学习编程 shell,我可以学习 bash shell 而不是 csh shell 脚本

标签: bash shell csh tcsh


【解决方案1】:

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

在文件顶部匹配您脚本的预期外壳。

【讨论】:

  • 以下代码的错误是 "if : Empty if" if ($1 == "one") echo "one" else if ($1 == "two") echo "two" else echo "no proper input" endif 当作为 ./script one 执行时
  • @Raghav 这是因为您的 if 语句缺少其 then 关键字。
  • 谢谢戈登..我不知道是否应该在同一行..现在代码正在运行
  • csh 和 tcsh 也允许有限的单行 if 语句:if (expr) stmt(区别在于缺少 then)——但该形式不允许 else .
【解决方案2】:

这是实际的脚本 -

#!/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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多