Test if a command outputs an empty string

Previously, the question asked how to check whether there are files in a directory. The following code achieves that, but see rsp’s answer for a better solution.


Empty output

Commands don’t return values – they output them. You can capture this output by using command substitution; e.g. $(ls -A). You can test for a non-empty string in Bash like this:

if [[ $(ls -A) ]]; then
    echo "there are files"
else
    echo "no files found"
fi

Note that I’ve used -A rather than -a, since it omits the symbolic current (.) and parent (..) directory entries.

Note: As pointed out in the comments, command substitution doesn’t capture trailing newlines. Therefore, if the command outputs only newlines, the substitution will capture nothing and the test will return false. While very unlikely, this is possible in the above example, since a single newline is a valid filename! More information in this answer.


Exit code

If you want to check that the command completed successfully, you can inspect $?, which contains the exit code of the last command (zero for success, non-zero for failure). For example:

files=$(ls -A)
if [[ $? != 0 ]]; then
    echo "Command failed."
elif [[ $files ]]; then
    echo "Files found."
else
    echo "No files found."
fi

More info here.

Leave a Comment