0

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
1
  • shellcheck.net will tell you what's wrong with your conditions. Commented Jul 22, 2018 at 3:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

My objective here is to exit from script if the count is not equals to 4. How to add that
@John, see revised answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.