Yam*_*iko 21 linux string bash comparison if-statement
我的脚本正在阅读并显示id3标签.我试图让它回应未知如果该字段是空白但我尝试的每个if语句将无法工作.id3标签是固定大小的,因此它们永远不会为空,但如果没有值,它们将填充空白区域.IE标题标签的长度为30个字符.到目前为止我已经尝试过
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计算结果为true但回声:$ x:it echos ::
剧本
#!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
Run Code Online (Sandbox Code Playgroud)
Cha*_*ffy 31
这些答案中的许多答案都比它们应该更复杂,或者更不易读.
[[ $string = *[[:space:]]* ]] && echo "String contains whitespace"
[[ $string = *[![:space:]]* ]] && echo "String contains non-whitespace"
Run Code Online (Sandbox Code Playgroud)
您可以使用bash的正则表达式语法.
它要求你使用双方括号[[ ... ]](一般来说更通用).
该变量不需要引用.不得引用 正则表达式本身
for str in " " "abc " "" ;do
if [[ $str =~ ^\ +$ ]] ;then
echo -e "Has length, and contain only whitespace \"$str\""
else
echo -e "Is either null or contain non-whitespace \"$str\" "
fi
done
Run Code Online (Sandbox Code Playgroud)
产量
Has length, and contain only whitespace " "
Is either null or contain non-whitespace "abc "
Is either null or contain non-whitespace ""
Run Code Online (Sandbox Code Playgroud)