rc.localでのRubyスクリプトの自動実行
起動時にスクリプトを実行する方法としていくつか方法があるが、ここでは比較的簡単にできるrc.localにスクリプトを書く方法を試してみる。
rc.localを編集
1
sudo nano/etc/rc.local
中身は以下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# Print the IP address
_IP=$(hostname-I)||true
if["$_IP"];then
printf"My IP address is %s\n""$_IP"
fi
exit0
例えば
mubogt_server_v1_0_0.rb
を
exit 0の前に
1
ruby/home/pi/mubogt_server_v1_0_0.rb
と書いて
再起動
1
sudo reboot
する。
スクリプトは
シェルスクリプトでもRubyやPythonの起動スクリプトでもいい。
ハマったのはデフォルトでrc.local内のスクリプトが自動起動しなかったこと
1
sh/etc/rc.local/mubogt_server_v1_0_0.rb
とすれば動くのでスクリプトには問題ない。
仕方ないので実行権を付与してみる。
1
sudo chmod+x/etc/rc.local
これで動いた。
デフォルトで動かないのは、こう書いてあるので当然ですね。
1
2
# In order to enable or disable this script just change the execution
# bits.
rc.local内のスクリプト
1
2
3
4
_IP=$(hostname-I)||true
if["$_IP"];then
printf"My IP address is %s\n""$_IP"
fi
は、起動するとIPアドレスを表示してくれます。
以前にjsayという日本語音声プログラムを試してみたので
これを
1
2
3
4
5
_IP=$(hostname-I)||true
if["$_IP"];then
printf"My IP address is %s\n""$_IP"
jsay"$_IP"
fi
と加えることで
起動時にIPアドレスをしゃべるようになりました。