1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【bash】文字列比較で、スペースを文字としてカウントしない方法

Last updated at Posted at 2020-03-16

文字列比較の落とし穴

bashにおいて、スペースのみを変数に代入した時も文字有りと判断されてしまう。

string=' '
test -n "${string}" && echo yes || echo no
# 比較演算子 n は1文字以上かを判定する。結果は yes

今回求める挙動

スペースだけで構成される文字列は、空(文字数0)と判定して欲しい。

求める挙動の実現方法

tr コマンドでスペースを除去した状態で判定する、だけ。

test -n $( echo "${string}" | tr -d " " ) && echo yes || echo no
# 結果は no
1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?