如何使用变量而不是文件来输出此 wc 命令

lau*_*hub 7 bash

我想从给定的偏移量读取文件,直到该文件的末尾。

我需要检索在此过程中读取的字节数,并将文件的输出重定向到其他地方。

这是我的脚本:

...some stuff here...
dd if=$file bs=1 skip=$skippedBytes | tee >(wc --bytes > $file.count) >(cat - >> $file.output) | $($exportCommandString $file)
byteCount=$(cat $file.count)
rm $file.count
echo "Number of read bytes: $byteCount"
Run Code Online (Sandbox Code Playgroud)

我希望“wc --bytes”部分将其返回值放在一个变量中,这样我就可以在不使用文件($file.count)的情况下使用它。

就像是:

dd if=$file bs=1 skip=$skippedBytes | tee >(byteCount=$(wc --bytes)) >(cat - >> $file.output) | $($exportCommandString $file)
echo "Number of read bytes: $byteCount"
Run Code Online (Sandbox Code Playgroud)

除了这样做,我的脚本挂起并且不起作用。

是否有可能做到这一点以及如何做到这一点?

rus*_*ush 4

您可以使用带有重定向的小技巧:

byteCount=$( exec 3>&1 ; 
     dd if=$file  bs=1  skip=$skippedBytes | tee -a >(wc -c >&3) $file.output |\
     $($exportCommandString $file) > /dev/null ;  3>&1   )
Run Code Online (Sandbox Code Playgroud)

它将所有输出重定向到您使用 exec 创建的 3,然后最后将其返回到 1。

您还需要将所有输出从 $exportCommandString 重定向到 /dev/null,否则它将与 wc 输出混合。

所有 stderr 将照常工作,没有任何变化。

ps:您可以使用tee -a file代替tee >(cat - >> file)).

pps:您无法从子 shell 导出变量,子 shell 总是|在 bash 或$(). 所以没有办法制作类似的东西

tee -a >(VAR=$(wc -c)) $file.output
Run Code Online (Sandbox Code Playgroud)