简体   繁体   English

在shell脚本中使用if的多个条件

[英]Multiple conditions with if in shell scripting

I want to check if a file exists or not along with the no of lines = 4 in a single if condition . 我想检查一个if条件中是否存在文件以及行数= 4。 Can anyone help here. 任何人都可以在这里帮忙。

if [[ -f report]] && [[`wc -l report` -eq 4 ]]; then
    echo " Proceed further"
else
    exit 1
fi

This is simpler: 这比较简单:

{ [ `wc -l < report` -eq 4 ] || exit; } 2>/dev/null 
echo " Proceed further"

Notes: 笔记:

  • If report exists and is 4 lines long, then wc -l report returns: 如果report存在并且有4行长,则wc -l report返回:

     4 report 

    ...which -eq can't understand. ... -eq无法理解。 Instead do wc -l < report which outputs an -eq -friendly: 而是执行wc -l < report ,输出-eq -friendly:

     4 
  • There's no need to check if report exists, since the < redirection will do that anyway, and returns the same error code. 无需检查报告是否存在,因为<重定向将始终执行该操作,并返回相同的错误代码。

  • More specific exit codes. 更具体的退出代码。 If report does not exist, the exit code is 2 . 如果报告不存在,则退出代码为2 If report is 5 lines long, the exit code is 1 . 如果report5行,则退出代码为1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM