[Bash] 文字列が空でないか判定する

作成日: 2026年09月23日

Bash で文字列が空でないか判定するには、-n を使用します。

下記の例では、変数 NAME に文字列が入っているため NAME is not empty を出力します。

NAME="Taro"
if [ -n "$NAME" ]; then
  echo "NAME is not empty"
else
  echo "NAME is empty"
fi

-n は、文字列の長さが 0 より大きい場合に true になります。

実行結果は下記のとおりです。

NAME is not empty
Bash Shell command