LoginSignup
0
0

More than 1 year has passed since last update.

bash test -n が常に true を返す場合の対処

Posted at

小ネタです。

test -n は文字列の長さが0 より 大きい場合にtrueを返します。

よって以下のコードは ZERO length を返すことが期待されます。

NO_STR=

if [ -n $NO_STR ]
then
    echo "NON ZERO length"
    return
fi
echo "ZERO length"

が結果としては、NON ZERO length が出力されます。
なぜ?

答えはこちら

結論としては、以下のようにダブルクォートで囲めばいいわけですな。

NO_STR=

if [ -n "$NO_STR" ]
then
    echo "NON ZERO length"
    return
fi
echo "ZERO length"

元のコードでは文字列が存在しない場合、 [ -n ] となり、これは常にtrueを返してしまうとのこと。
なるほどなー。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0