Reputation: 8629
I want to compare the output of tail -1 to see if it's an empty string. For instance, if I am searching for a file with find, and I want to compare the result to "" (empty string), how do I do that? I have:
find . -name "*.pdf" | tail -1 | xargs -L1 bash -c 'if [$1 == ""] then echo "Empty"; else
< echo $1; fi'
Basically, it will print out the file name if it's not empty, and will print "Empty" if there are no pdf files found by 'find'.
I've tried a number of different variations with using the if-else statements inside a single command, and nothing seems to work.
Upvotes: 1
Views: 4772
Reputation: 1386
With xargs
you can use the option --no-run-if-empty
.
--no-run-if-empty
-r
If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.
My use case exemple:
find /iDontExist | xargs du -sc
# produce the command `du -sc` on the current directory
# that wasn't the initial aim
A way to avoid this:
find /iDontExist | xargs --no-run-if-empty du -sc
hth
Upvotes: 2
Reputation: 567
You could make a script:
#!/bin/bash
output=$(find . -name *.pdf)
if [ -z $output ]; then
echo "Empty"
fi
Upvotes: 0
Reputation: 75548
You can use a function instead.
function tailx {
if read -r LINE; then
(
echo "$LINE"
while read -r LINE; do
echo "$LINE"
done
) | command tail "$@"
else
echo "Empty."
fi
}
You can place that in ~/.profile
or ~/.bashrc
. Run exec bash -l
to reload your bash and run find . -name "*.pdf" | tailx -1
. You can also customize that to become a shell script placed /usr/local/bin
as /usr/local/bin/tailx
instead. Just add tailx "$@"
at the end of the script, and add the shell header at the beginning.
#!/bin/bash
...
tailx "$@"
Upvotes: 1
Reputation: 871
Try this:
find . -name "*.pdf" | xargs -L1 bash -c 'if [ -s $0 ] ; then echo "$0"; else echo "File empty"; fi'
According to man test
-s will check to see if the file size is zero.
Upvotes: 3
Reputation: 123608
You don't need to pipe output to tail
, xargs
, and so on...
Simply say:
(( $(find . -name "*.pdf" | wc -l) == 0)) && echo "Empty"
Upvotes: 1