tar ボールの中から特定の「ファイルのみ」を抽出したいケースがあります。 たとえば、GitHub Releases で公開された tar ボールから、シングルバイナリのみを抽出して PATH の通った場所に置きたいケースです。
これをシンプルに行う方法についてです。
ファイルのみの抽出方法
たとえば、以下のようなディレクトリを tar.gz で固めた archive.tar.gz があるとしましょう。ここから、file2 のみを抽出したい。
$ tree dir dir ├── file1 ├── file2 └── file3
結論から言えば、以下で可能です。
$ tar zxf archive.tar.gz --strip-component 1 dir/file2
実行後、カレントディレクトリに file2 ファイルができている(抽出されている)ことがわかります。
もし、シングルバイナリを直接 PATH の通ったディレクトリに配置したければ、-C を付与しましょう。
$ tar zxf archive.tar.gz -C bin --strip-component 1 dir/file2
ポイント
単純に tar zxf を行った場合、通常はディレクトリ構造が保存されたまま抽出されます。以下を見てみると、 file2 ではなく、dir/file2 として抽出が行われていることがわかります。
$ tar zxf archive.tar.gz dir/file2 $ ls dir/ ./ ../ file2
ここで dir が不要なんだけど、ということであれば、活躍するオプションが --strip-component です。 以下は man から引用しますが、引数に与えた数だけディレクトリ階層を切り取ってくれることがわかります。
--strip-components count
Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after checking inclusion/exclusion patterns but before security checks.