4
2

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 5 years have passed since last update.

サーバ起動時にtmuxのセッションでコマンドを実行する方法

Last updated at Posted at 2019-05-24

したいこと

tmux(screen系)コマンドを使うことでコマンドを実行しつつ、他の作業を続けることができます。
サーバのメインで実行させたいコマンドをtmuxのセッションで実行しておけば、サーバにsshで入った際に メインコマンドを止めず にログ確認などが行えて便利です。

起動コマンドに登録して、サーバを立ち上げればその状態になるようにしたいと思います。

tmuxで別セッションでコマンドを実行するには

別セションでコマンドを実行するのは、以下の書式です。

別セッションでコマンド実行

tmux new-session -d '実行したいコマンド'

セッションに移動せずにコマンドを実行します。

tmux a で、セッションを移動して実行出来ていることを確認しましょう。

なお、tmux new-session -d 'ls'のように実行して即終了するコマンドだとセッションが残らないようです。
topコマンドのように動き続けるコマンドで試してください。

自動起動へ登録する

tmuxの動きは判ったので登録します。

cron登録エディタ
crontab -e

cron登録エディタを開き、以下の書式で登録してください。
今回は、起動時に動いてほしいので、 @reboot で登録します。

コマンドを起動時にtmuxセッションで実行するように登録
@reboot (. ~/.profile; tmux new-session -d 'hogeCommand fugaOption')

('hogeCommand fuga_option'を任意のコマンドに変更してください)

サーバをrebootすると、tmuxが立ち上がっており、セッションでコマンドも実行されているはずです。

以上です。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?