LoginSignup
0
0

Ruby芸160チャレンジ(#24)終了時の処理

Last updated at Posted at 2023-12-23

この記事は何

shellgei160を通じて言語習得 Advent Calendar 2023に参加しています。

書籍「シェル芸ワンライナー160本ノック」の例題をRubyで解いてみて、Rubyの学習に役立てようとするものです。

例題はこちらのリポジトリで公開されているものに限ります。
https://github.com/shellgei/shellgei160

実行環境など

  • Docker image: ruby:3.0.2
  • 上記リポジトリをクローンした上で、リポジトリのルートディレクトリ直下にanswer-rubyディレクトリを作り、その中に解答となるファイルを作成していきます。

今回のテーマ

$ trap 'rm ~/tmp/*' EXIT

# 別解
$ echo 'rm ~/tmp/*' >> ~/.bash_logout

これは元のtrapを使うのが鮮やかですね…。

シェル終了時の処理を定めるなら`~/.bash_logout'に処理を書き込むしかないですかね…?

File.open(File.expand_path('~/.bash_logout'), 'a') do |f|
  f.puts('rm ~/tmp/*')
end

または、スクリプトの終了時の処理を定めるならこんな感じ…?

at_exit do
  system('rm ~/tmp/*')
end

所感

  • ホームディレクトリ(~)の展開を勝手にしてくれないのは意外
  • システムコマンドの実行はsystemでできるんですね
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