My script uses a tmp file where it writes and deletes data. I use redirections to write, and sed to delete.

At some moment, I want to check if the file exists and is empty, but my code fails (the file exists and has no data):

[[ -s /tmp/tmp_file ]] && echo "not empty" || echo "empty"
not empty

When I check the file size, it shows 1 byte, despite that the file has no data in it.

If I open the file with gedit and save the file, then it shows 0 byte size.

Why is this happening?

How to be sure that, deleting contents, no extra byte is left?

Added outputs of ls -ld and od, when the file is "empty" (one byte):

ls -ld tmp_file
-rwxr-xr-x 1 root root 1 dic 18 15:43 tmp_file

od tmp_file
0000000 000012

Image showing the one byte size:

enter image description here

Image of the file opened in gedit:

enter image description here

  • Can you show the output of ls -ld and od on the file in question when it's in the state where you think it's supposed to be empty but is not? – Kusalananda Dec 18 '19 at 18:08
  • How do you know that it is empty (show in question)? – ctrl-alt-delor Dec 18 '19 at 18:40
  • @Kusalananda updated the question with the commands required. – guillermo chamorro Dec 18 '19 at 18:52
  • @ctrl-alt-delor updated question. – guillermo chamorro Dec 18 '19 at 19:02
  • That file contains a single newline character (it is a file with one empty line). – Kusalananda Dec 18 '19 at 19:08

I am going to take a guess that you are using echo to write to the file, which is appending a newline character and when you delete with sed, you are not matching the newline when deleting.

There are a few options here:
1: use printf or (echo -n if supported) to write without trailing newlines.
2: match the trailing newlines with sed to remove it/them.
3: Steve's method of emptying file when appropriate.

  • 1
    Thanks! You are right, I use echo to add new lines, echo -n did the trick. – guillermo chamorro Dec 18 '19 at 19:17

1 byte file, containing a \n only.

Use >/tmp/foo to zero it.

$ ls -l /tmp/foo
-rw-rw-r--. 1 steve steve 1 Dec 18 12:50 /tmp/foo
$ od -c /tmp/foo
0000000  \n
$ >/tmp/foo
$ ls -l /tmp/foo
-rw-rw-r--. 1 steve steve 0 Dec 18 12:51 /tmp/foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.