AJW
AJW

Reputation: 5873

bash check for empty string/line using -z

I am relatively new to bash scripting, and I have the following script, which is not giving me results I expect. So, my script looks like so:

#!/bin/bash

echo "Today is $(date)"
shopt -s nullglob

FILES=/some/empty/dir/with/no/text/files/*.txt
#echo $FILES


if [ -z "$FILES" ]
then
    echo 'FILES variable is empty'
    exit
else
    echo 'FILES variable is not empty'
    echo 'done' > write_file_out.dat
fi

So, the directory I am trying to use FILES on is completely empty - and still, when I do if [ -z "$FILES" ] it seems to say that it is not empty.

Baffled by this - wondering if someone can point me in the right direction.

Upvotes: 2

Views: 347

Answers (1)

anubhava
anubhava

Reputation: 786091

Instead of:

FILES=/some/empty/dir/with/no/text/files/*.txt

You need to use:

FILES="$(echo /some/empty/dir/with/no/text/files/*.txt)"

Otherwise $FILES will be set to: /some/empty/dir/with/no/text/files/*.txt and this condition [ -z "$FILES" ] will always be false (not empty).

You can also use BASH arrays for shell expansion:

FILES=(/some/empty/dir/with/no/text/files/*.txt)

And check for:

[[ ${#FILES[@]} == 0 ]]

for empty check.

Upvotes: 5

Related Questions