简体   繁体   中英

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 . 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:

     4 report 

    ...which -eq can't understand. Instead do wc -l < report which outputs an -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 . If report is 5 lines long, the exit code is 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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