John
John

Reputation: 23

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

Upvotes: 0

Views: 144

Answers (1)

agc
agc

Reputation: 8446

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.

Upvotes: 1

Related Questions