【问题标题】:Shell script to search for a pattern in a file using if else使用 if else 在文件中搜索模式的 Shell 脚本
【发布时间】:2018-08-28 14:37:49
【问题描述】:

这是我的脚本,我想在文件中查找模式。如果找到模式,我知道grep -q '<Pattern>' '<file>' && echo $? 的退出状态为 0。但我收到 if: Expression Syntax 错误。

 if ( (grep -q '<Pattern>' '<file>' && echo $?)==0  ) then
 echo "Pattern found"
 else
 echo "Pattern not found"
 endif

【问题讨论】:

  • 我不知道 tcsh,但是在 bash 和 POSIX sh 中,你只需要 if grep -q '&lt;pattern&gt;' '&lt;file&gt;'; then
  • 我也会在 tcsh 中这样做:sh -c 'if grep -q "&lt;Pattern&gt;" "&lt;file&gt;"; then ... ' :)
  • 顺便说一句,shell 标签通常专注于 POSIX 系列外壳;最好在此处坚持使用cshtcsh 标签,以避免吸引一群考虑使用csh severely misguided 的人。

标签: linux shell scripting tcsh


【解决方案1】:

我想你想要这个:

if ( { grep -q '<Pattern>' '<file>' } ) then
 echo "Pattern found"
else
 echo "Pattern not found"
endif

注意命令周围的大括号以及大括号和命令之间的空格。

man tcsh表达式

命令退出状态

可以在表达式中执行命令并返回其退出状态 通过将它们括在大括号 ('{}') 中。请记住,大括号应该是 与命令的单词之间用空格隔开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2015-06-06
    相关资源
    最近更新 更多