简体   繁体   English

tar `--to-command`:如何将 output 发送到自定义 function?

[英]tar `--to-command` : how to send output to a custom function?

I have a very many tar archives I need to extract files from and perform post processing on (amongst other things, changing file encodings and applying some sed commands).我有很多 tar 存档,我需要从中提取文件并对其执行后处理(除其他外,更改文件编码和应用一些sed命令)。 I'm interesting in using tar 's --to-command option to apply a custom function which does all of those things in sequence.我对使用tar--to-command选项应用自定义 function 很感兴趣,它按顺序执行所有这些操作。

Up until now, I have been doing:到目前为止,我一直在做:

tar -xzi --to-command=<line of shell commands>

Unfortunately, the list of commands I need to do has got larger and means it is no longer neat (nor probably sensible) to attempt to do everything on one line.不幸的是,我需要执行的命令列表变大了,这意味着尝试在一行中完成所有操作不再整洁(也可能不明智)。

To neaten things up, I've written function in another file, test-function.sh , which (tries to) perform those things in sequence:为了整理一下,我在另一个文件 test-function.sh 中编写了test-function.sh ,它(尝试)按顺序执行这些操作:

#!/bin/bash

post_extract() {
    <the things I need to do>
}

I realise the above is example is incomplete, but my problem at the moment is that I can't get --to-command to find the post_extract function to even go about testing it.我意识到上面的例子是不完整的,但我现在的问题是我无法通过--to-command找到post_extract function 甚至 go 来测试它。

Where should I put post_extract / what would be the idiomatic way of exposing it to tar 's --to-command ?我应该把post_extract放在哪里/将它暴露给tar--to-command的惯用方式是什么?

Given the behaviors demonstrated in TAR with --to-command , (in particularly, --to-command='md5sum |...' resulting in md5sum: |: No such file or directory ), it's clear that tar --to-command doesn't invoke a shell, but simply performs shell-like parsing and then attempts an execv() -family invocation of the resulting command.鉴于TAR 中使用 --to-command演示的行为(特别是--to-command='md5sum |...'导致md5sum: |: No such file or directory ),很明显tar --to-command不会调用 shell,而只是执行类似 shell 的解析,然后尝试对生成的命令执行execv()系列调用。 This means the target command needs to be something that can actually be executed -- a script, or similar.这意味着目标命令需要是可以实际执行的东西——脚本或类似的东西。

This behavior is (loosely) documented in theRunning External Commands section of the GNU tar documentation.此行为(松散地)记录在 GNU tar 文档的运行外部命令部分中。


One way around this is to have the thing that's invoked be a shell , and then use an exported function to ship code from your parent shell to that child process;解决这个问题的一种方法是让被调用的东西成为 shell ,然后使用导出的 function 将代码从父进程 shell 发送到该子进程; as shown below:如下所示:

#!/usr/bin/env bash
#              ^^^^- MUST be bash, not sh

post_extract() {
  : "do stuff here"
}

export -f post_extract
tar --to-command $'bash -c \'post_extract "$@"\' _' ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM