LoginSignup
3
4

More than 5 years have passed since last update.

touch時に空のファイルではなくテンプレートから作成する

Last updated at Posted at 2017-06-05

touchコマンドは基本的には、新しいファイルの作成に使われている。

しかし、touchは空のファイルを作成するのであまり便利ではない。
例えば、licenseファイルをプロジェクトに含め忘れたので後から追加したいとする。
そのとき叩くのは、touch licenseもしくは、既存のプロジェクトからlicenseを探してcpをする。

ここで思い至るのは、licenseファイルの内容はほぼ変わることがない。だいたい以下のような感じである。

The MIT License (MIT)

Copyright (c) akameco <akameco.t@gmail.com> (akameco.github.io)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
(略)

となると、これをテンプレートとしてtouchの代わりにこれを新しいファイルとして作成した方が良さそうだ。

そこで、touchの代わりにtouch-altを使う。

touch-alt

$ npm i -g touch-alt

touch-alt

akameco/touch-alt: Create from a template instead of a new file

使い方はtouchと同じだが、touchの本来の機能であるタイムスタンプ更新の機能はない。
自分はほぼ使わないのでalias touch=touch-alt.zshrcに追記した。

使い方はtouchと同じだ。
だが、--addもしくは-aフラグで新しいテンプレートを追加できる。
追加されたファイルは~/.touch-alt以下に保存される。

$ touch-alt --add license

後は、touchの代わりにtouch-altlicenseを作成するだけだ。

$ touch license
$ cat license

$ rm license
$ ls -la ~/.touch-alt
.             ..            license
$ touch-alt license
$ cat license
The MIT License (MIT)

Copyright (c) akameco <akameco.t@gmail.com> (akameco.github.io)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
()

もちろん、テンプレートがないファイルは空ファイルを作成する。

まとめ

自分はわりとyeomenでテンプレートを作成することが多いが、既存のプロジェクトにわりといつも使う設定を持ってきたいときに便利であると思う。
例えば、.babelrcや.eslinrc.editorconfigなどがそれだ。
これらをtouch -a .eslintrcとしておくことで、touch .eslintrcをするだけでプロジェクトに追加できる。

akameco/touch-alt: Create from a template instead of a new file

実際のところ、すでにテンプレートが保存してあればそれをコピーしてくるだけのスクリプトだが、この手のスクリプトはどうやってもtestの方が行数が増えるのが面倒なところだった。

$ touch-alt --help

  Create from a template instead of a new file

  Usage
  $ touch-alt <source>
  $ touch-alt --add <source>

  Options
  -a, --add         Create new template file
  -o, --overwrite   Overwrite by template

  Example
  $ touch-alt .editorconfig
3
4
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
3
4