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

三項演算子で偶数・奇数を判定する

Last updated at Posted at 2022-04-01

shell勉強中のメモ。

三項演算子とは

構文
condition ? exprIfTrue : exprIfFalse

引数

  • condition
    • true(真)かfalse(偽)かの評価をしたい式
  • exprIfTrue
    • conditiontrue(真) と評価された場合に実行される式
  • exprIfFalse
    • conditionfalse(偽)と評価された場合に実行される式

たとえば

$ seq 4 | awk '{print $1%2 ? $1"奇数":$1"偶数"}'
1奇数 #2の剰余が1(条件式は真)
2偶数 #2の剰余が0(条件式は偽
3奇数 #2の剰余が1(条件式は真)
4偶数 #2の剰余が0(条件式は偽
$ 

seq 4

1
2
3
4

を出力した後、引数÷2($1%2)で判定しています。
awkでは条件式の値が0や空白、空文字の場合に偽です。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?