2

通过 tcsh 执行 IF 语句时遇到问题。这对我来说很好 -

#!/bin/bash
if echo `cal|tail -6|sed -e 's/^.\{3\}//' -e 's/.\{3\}$//' |tr -s '[:blank:]' '\n' | head -11|tail -10|tr -s '\n' ' '`|grep -w `date "+%e"`
then
        echo "present"
else
        echo "absent"
fi

这就是问题 -

#!/bin/tcsh
if echo `cal|tail -6|sed -e 's/^.\{3\}//' -e 's/.\{3\}$//' |tr -s '[:blank:]' '\n' | head -11|tail -10|tr -s '\n' ' '`|grep -w `date "+%e"`
then
        echo "present"
else
        echo "absent"
endif

收到此错误-

if: Expression Syntax.
then: Command not found.

我真的需要使用“tcsh”来运行它

4

3 回答 3

3

首先,您必须知道可以找到两个不同的 shell 系列:

  • Bourne 类型的 shell(Bash、zsh...)
  • C 语法类型 shell (tcsh, csh...)

如您所见,Bash 和 tcsh 不是来自同一个 shell 系列。因此,在 tcsh 上,if 语句与 bash 语句有点不同。在您的情况下,关键字“then”放错了位置。尝试将其放在“if”行的末尾:

#!/bin/tcsh
if(echo `cal|tail -6|sed -e 's/^.\{3\}//' -e 's/.\{3\}$//' \
|tr -s '[:blank:]' '\n' | head -11|tail -10|tr -s '\n' ' '`| \
grep -w `date "+%e"`) then
     echo "present"
else
     echo "absent"
endif

希望能帮助到你。

于 2012-11-14T10:49:52.547 回答
0

之所以有效,bash是因为ifPOSIX 样式的 shell 中的语句总是通过执行命令来工作(而且它恰好[是命令的别名test)。

但是,if中的语句tcsh不是这样工作的。它们有自己的语法(在tcsh手册页中的表达式下描述)。

尝试自行运行管道,然后检查退出状态if

cal | tail -6 | sed -e 's/^.\{3\}//' -e 's/.\{3\}$//' | tr -s '[:blank:]' '\n' | head -11 | tail -10 | tr -s '\n' ' ' | grep -w `date "+%e"` >/dev/null
if ( $? == 0 ) then
    echo "present"
else
    echo "absent"
endif
于 2012-12-17T20:43:45.307 回答
0

我通常会做这样的事情,保持条件语句简单。但是,您可以将变量填入“if”中,然后检查您的 grep 是否为空。

set present = `tail -6 .... | grep “”`

if ( $present != “” ) then
   echo “present”
else
   echo “not present”
endif 

您还可以使用“-x”来帮助调试#!/bin/tcsh -x。这么小的东西,检查变量的回声应该可以做到,但是“-x”可能会给你所有你需要的信息。

于 2017-12-19T13:43:57.473 回答