A
A
Artem Melnykov2019-05-12 07:23:23
linux
Artem Melnykov, 2019-05-12 07:23:23

How to solve a problem in Bash?

There is a code:

#!/bin/bash

if [ -s file.txt ]
then
echo "File is empty"
else
count=1
cat file.txt | while read line
do
echo "$line"
count=$(( $count + 1 ))
done
fi

However, the file is not empty, but the script still reports that the file is empty. How to decide?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Saboteur, 2019-05-13
@NickProgramm

-s checks that the file exists and is NOT empty.
if you want to use test, then the logic is this:

if [ -f file.txt ]; then
  if [ -s file.txt ]; then
    echo "file.txt is not empty
  else
    echo "file.txt is empty"
  fi
else
  echo "file.txt doesn't exists"
fi

Can it be like this
if ; then
  echo "file.txt is empty"
else
  echo "file.txt doesn't exist or not empty"
fi

J
jcmvbkbc, 2019-05-12
@jcmvbkbc

if [ -s file.txt ]
then
echo "File is empty"

Wrong test:
-s FILE
              FILE exists and has a size greater than zero

The correct test for a file of size zero would probably look like this:
But then the further logic in the else will fall apart, because the else branch will now mean "no file, not a regular file, or a file of non-zero size".

V
Vladimir Mukovoz, 2019-05-12
@castomi

To you in the first answer resulted from docks the quote. It says the file exists and has a size greater than zero, so when the condition is met, it cannot be empty in any way), it is empty in else.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question