Ansatzの備忘録

勉強したことあるいはふと思い立ったこと

シェルワンライナー160本ノック問題26

問題26 18時を過ぎたら帰りましょう

18時から明け方4時までの間にコマンドを実行すると「早く帰れ」とメッセージが出るようにbashの設定ファイルにワンライナーを記述するという問題だった。まったくわからなかった。

この問題は子供のプロセスが終了したときに親プロセスが受け取るSIGCHLDをどう使うか、という問題だったらしい。

解答は

trap 'h=$(date +%-H);[ "$h" -ge 18 -o "$h" -lt 3 ] && echo 早く帰れ' SIGCHLD

となる。 date +%-H でゼロ埋めしない状態で時刻を出力している。

‘-’
     (hyphen) Do not pad the field; useful if the output is intended for
     human consumption.

 

If given an argument that starts with a ‘+’, ‘date’ prints the
current date and time (or the date and time specified by the ‘--date’
option, see below) in the format defined by that argument, which is
similar to that of the ‘strftime’ function.

という仕様なので、この場合現在時をゼロ埋めしないで出力することになる。

テストコマンド中の -o はORの意味を持つらしい。マニュアルを調べても出てこなかったがググると出てきた。ちなみに -a だとANDになる。