LoRa モジュール LRA1 にプログラムを転送しようとしたが、コピペだと処理が追いつかなくて取りこぼす。なのでウェイトをかけながら転送したい。ここでは転送に応用するために、ウェイトを書けながらファイルを表示するスクリプトについて考えてみる。
使い捨てできるようにワンライナーで。
環境
- bash (Ubuntu 22.04 LTS)
$ bash --version
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
ウェイトをかけながらファイルを表示する
一行ごとに0.5秒のウェイトをかける
while read line; do echo $line;sleep 0.5; done < test.bas
一文字ごとに0.1秒のウェイトをかける
while IFS= read -rN1 char; do if [ '%' = "$char" ];then printf "%%";else printf "$char";fi; sleep 0.1; done < test.bas
最初は単に
while IFS= read -rN1 char; do printf "$char"; sleep 0.1; done < test.bas
としてましたが、test.bas に % が含まれているとそこで printf:
%': missing format character` エラーが出ました。 printf の代わりに echo -n を使おうとしましたが、改行が無視されてしまいますね。
そこで上のように %
かどうか判定するようにしたのですが、 '%' = $char
としていたら今度は bash: [: %: unary operator expected
エラー。調べてみたら、'%' = "$char"
とすれば 変数の中身を解釈せずに処理するらしいです。
CRLF を変換するフィルターを追加して、1秒ごとに1行表示する
test.bas は Linux の LF 改行コード。CRLFに変換しながら表示します。
while read line; do echo -n $line ; printf "\r\n";sleep 1; done < test.bas
最初は
while read line; do printf "$line\r\n";sleep 1; done < test.bas
としていましたが、やはり %
とか \
とかがエラーが出るので、それらを解釈しない echo -n を使用しました。