My script is reading and displaying id3 tags. I am trying to get it to echo unknown if the field is blank but every if statement I try will not work. The id3 tags are a fixed size so they are never null but if there is no value they are filled with white space. I.E the title tag is 30 characters in length. Thus far I have tried
echo :$string: #outputs spaces between the 2 ::
if [ -z "$string" ] #because of white space will always evaluate to true
x=echo $string | tr -d ' '; if [ -z "$string" ];
#still evaluates to true but echos :$x: it echos ::
the script
#!bin/bash
echo "$# files";
while [ "$i" != "" ];
do
TAG=`tail -c 128 "$i" | head -c 3`;
if [ $TAG="TAG" ]
then
ID3[0]=`tail -c 125 "$1" | head -c 30`;
ID3[1]=`tail -c 95 "$1" | head -c 30`;
ID3[2]=`tail -c 65 "$1" | head -c 30`;
ID3[3]=`tail -c 35 "$1" | head 4`;
ID3[4]=`tail -c 31 "$i" | head -c 28`;
for i in "${ID3[@]}"
do
if [ "$(echo $i)" ] #the if statement mentioned
then
echo "N/A";
else
echo ":$i:";
fi
done
else
echo "$i does not have a proper id3 tag";
fi
shift;
done
You can use bash's regex syntax.
It requires that you use double square brackets
[[ ... ]]
, (more versatile, in general).The variable does not need to be quoted. The regex itself must not be quoted
Output
Sharing a more portable method not requiring double-brackets [[ ]] while keeping it simple, as much as possible.
Detect a string containing ONLY white space or = null:
Which in this case would be:
Such as:
What this does is simply replace all white space with null through substitution. If $string contains only white space, the -z test will evaluate TRUE. If there are non-white space characters in the string, the equation evaluates to FALSE.
Elaborating further on BASH (since OP asked about this in BASH), the example above will not catch tabs, though it is possible to do so. Here are more examples in BASH that do and don't work as expected.
Let's say there's a tab in the search string.
This works:
But these don't:
The two last examples above both report the string is not empty. If you consider a tab to be white space, that would be a problem and you'd want to use the first example.
What about newline? Let's take a look at an
\n
scenario. First off, "correct" behavior depends on your expectations.These treat newlines (
\n
) as white space (equation evaluates TRUE):This doesn't (equation evaluates to FALSE), meaning this equation thinks a newline is not white space.
If you require checking for newlines and tabs and spaces, you may need to use two IF/THEN statements or the CASE method described above.
That compresses all repeated spaces down to one space, and compares for that.
With extended globs enabled (
shopt -s extglob
):This one checks for Zero length or SPACE or TAB
A non-bash specific, shell only variant: