2

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.

1 Answer 1

5

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.

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

17 Comments

Or FILES=(/some/empty/dir/with/no/text/files/*.txt) and then test for an empty array since that is much better to work with when you actually need to do something with the files.
files will NOT be set to /some/empty/dir/with/no/text/files/*.txt because I am using shopt -s nullglob You can try using echo $FILES to see this
@AJW, but you were quoting the variable: [ -z "$FILES" ] -- that prevents filename expansion. That's also the difference between echo $FILES and echo "$FILES". When you declare the variable, filename expansion does not happen, not until you use the variable.
thanks a tonne @anubhava - I used your bash arrays for shell expansion (thanks also to @EtanReisner) - and it works perfectly.
ok - got it - thanks again! Think I have solved it - obviously, with your help :)
|

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.