Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | CLI | Play Well with Others | Using Exit Codes to Report Success or Failure

概要

書籍 Build Awesome Command-Line Applications in Ruby2

Play Well with Others

詳細

exit code はアプリケーション終了時の成否を伝える。
exit code が 0 なら成功。
それ以外なら失敗。

シェルの $? にステータスが格納されています。

サンプル仕様

テキストを大文字、小文字変換するアプリケーション。
テキストが指定されなかった場合や、空文字の場合はエラー。

サンプル

require 'optparse'
require 'pp'

options = {}
opts = OptionParser.new do |opts|
  opts.on("-u", "--upcase", "大文字に変換します"){ |v| options[:upcase] = true }
  opts.on("-d", "--downcase", "小文字に変換します"){ |v| options[:downcase] = true }
  opts.program_name = "up_down_converter"
  opts.version = "0.0.1"
  opts.banner = <<-EOS
テキストを大文字か小文字に変換して出力します。

Usage: #{opts.program_name} [options] text
  EOS
end
opts.parse!(ARGV)
pp options

text = ARGV.first

exit false if text.nil? || text.empty?

if options[:upcase]
  puts text.upcase
elsif options[:downcase]
  puts text.downcase
else
  puts text
end

出力

# 引数なし(エラーになる)
$ ruby 1.rb
{}
$ echo $?
1

# 引数あり(正常終了)
$ ruby 1.rb HoGe
{}
HoGe
$ echo $?
0