シェルスクリプトで文字列が空でもスペースでもないかどうかをチェックする 質問する

シェルスクリプトで文字列が空でもスペースでもないかどうかをチェックする 質問する

文字列がスペースでも空でもないかどうかを確認する次のシェル スクリプトを実行しようとしています。ただし、上記の 3 つの文字列すべてに対して同じ出力が表示されます。"[[" 構文も使用してみましたが、効果はありませんでした。

これが私のコードです:

str="Hello World"
str2=" "
str3=""

if [ ! -z "$str" -a "$str"!=" " ]; then
        echo "Str is not null or space"
fi

if [ ! -z "$str2" -a "$str2"!=" " ]; then
        echo "Str2 is not null or space"
fi

if [ ! -z "$str3" -a "$str3"!=" " ]; then
        echo "Str3 is not null or space"
fi

次のような出力が得られます。

# ./checkCond.sh 
Str is not null or space
Str2 is not null or space

ベストアンサー1

の両側にスペースが必要です!=。コードを次のように変更します。

str="Hello World"
str2=" "
str3=""

if [ ! -z "$str" -a "$str" != " " ]; then
        echo "Str is not null or space"
fi

if [ ! -z "$str2" -a "$str2" != " " ]; then
        echo "Str2 is not null or space"
fi

if [ ! -z "$str3" -a "$str3" != " " ]; then
        echo "Str3 is not null or space"
fi

おすすめ記事