Kekeの日記

エンジニア、読書なんでも

CLIツールを作る上で知っとくべき用語

本記事

本記事では、CLIツールを作る時に出てくるフラグオプションサブコマンドなどの用語を解説することで、どんな言語でもCLIツールを開発できるようになることを目的に解説します。

用語

Command: コマンド

コンピュータに命令を出すためのものです。

以下のように例えばlsコマンドならばbin/以下にあります。

$ which ls

/bin/ls

一体どんなコマンドなのかというとmanコマンドで確認することができます。

ここでNAMEではどんなコマンドなのかが書かれています。

$ man ls

NAME
     ls -- list directory contents

SYNOPSIS
     ls [-ABCFGHLOPRSTUW@abcdefghiklmnopqrstuwx1] [file ...]

DESCRIPTION
     For each operand that names a file of a type other than directory, ls displays its name as well as any requested, associated information.  For each operand that names a file of type directory, ls displays the names of files contained
     within that directory, as well as any requested, associated information.

     If no operands are given, the contents of the current directory are displayed.  If more than one operand is given, non-directory operands are displayed first; directory and non-directory operands are sorted separately and in lexicographi-
     cal order.

     The following options are available:
    ...

Subcommand: サブコマンド

サブコマンドは以下のように、コマンドに続いて記述するものです。

主にコマンド内の、さらに特定のコマンドを呼び出す時に使われ、機能が一つ以上あるものに対して定義されていることが多いです。

たとえばgitコマンドならば

  • git push
  • git add
  • git checkout

などいろんなサブコマンドがあり、それぞれが明確な用途に分かれています。

例えばgit push --helpをします。

$ git push --help

NAME
       git-push - Update remote refs along with associated objects

SYNOPSIS
       git push [--all | --mirror | --tags] [--follow-tags] [--atomic] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
                  [--repo=<repository>] [-f | --force] [-d | --delete] [--prune] [-v | --verbose]
                  [-u | --set-upstream] [--push-option=<string>]
                  [--[no-]signed|--signed=(true|false|if-asked)]
                  [--force-with-lease[=<refname>[:<expect>]]]
                  [--no-verify] [<repository> [<refspec>...]]

     ...

このようにあります。

Args: 引数

例えばgit pushの後に続くものは引数です。

git push hoge fuga

ここでhogefugaはコマンドではなくて、引数として情報を渡しているにすぎません。

このようなものをargsと呼び、いくつも引数Parsarがあります。

Option: オプション

オプションはコマンド、またはサブコマンドに対して情報を渡せます。

また、以下の二つのオプションがあります。

  • -h: ショートオプション
  • `--hoge: ロングオプション

先ほどのgit pushでは

 git push [-n | --dry-run]

  • -n: ショートオプション
  • --dry-run: ロングオプション

があるということです。

どっちを使えばいいのかというと一般的にはロングオプションの方が説明的で好まれます

www.franzoni.eu

また、値をとるオプションもあります。例えばGoogle Cloud PlatfromのCLIツールは以下のようになっています。

gcloud ... --zone="asia-northeast1-a"

このようにオプションに値を付与することができるものもあります。

flag: フラグ

ちょっとオプションと区別がつかないかもしれません。フラグとは-fのように0か1かの設定をするために使うものです。

例えばgit pushでは

git push origin master --force

or 

git push origin master -f

とすることができます。

この様なものはフラグと呼ばれています。

まとめ

今回、説明した用語を知れば、どの言語でも開発に取り組むことはできるのではないかと思います。