bash - Checking empty file returns as non-empty -


when i'm using 1 of comparison operators/functions on empty file, bash returns file not empty. there must newline character or something, it's making these tests pass when shouldn't.

so there way test if file has character? i've tried [ -s file.txt ], [ -n file.txt], , brethren, return file.txt not empty.

i've tried doing cat , assigning variable, variable read not empty reason.

any other way see if file empty?

edit here's i've done. cleared file (ctrl+a , delete). made sure when tried moving cursor cursor doesn't move. did if [ -n filename ] ; echo "not empty"; fi; returns not empty

the test non-empty file is:

[ -s file.txt ] 

the test empty file, therefore, is:

[ ! -s file.txt ] 

or can use bash's ! operator outside test command:

if ! [ -s file.txt ] 

note these operations consider file 'empty' if contains 0 bytes. if bigger that, not empty definition. if want inspect contents , ignore file contains blanks , newlines, etc, need different test altogether.

you can consider using [[ command (a shell built-in number of special semantics) instead of [, though in context, makes no practical difference. [[ command not portable [.

note -n option tests non-empty string (not non-empty file).

[ -n file.txt ] 

will pass (because file.txt not empty string). used variables:

[ -n "$variable" ]    # $variable non-empty [ -z "$emptyvar" ]    # $emptyvar empty 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -