Bar*_*den 22 command-line gzip
我正在编写一个脚本,其中我正在压缩文件。
有可能我可能会压缩一个文件,创建一个同名的文件,并尝试对其进行 gzip,例如
$ ls -l archive/
total 4
-rw-r--r-- 1 xyzzy xyzzy 0 Apr 16 11:29 foo
-rw-r--r-- 1 xyzzy xyzzy 24 Apr 16 11:29 foo.gz
$ gzip archive/foo
gzip: archive/foo.gz already exists; do you wish to overwrite (y or n)? n
not overwritten
Run Code Online (Sandbox Code Playgroud)
通过使用gzip --force,我可以强制 gzip 覆盖foo.gz,但在这种情况下,我认为如果覆盖 ,我很有可能会丢失数据foo.gz。似乎没有命令行开关来强制 gzip.gz单独保留文件......在提示符下按 'n' 的非交互式版本。
我试过gzip --noforce和gzip --no-force,希望这些可能遵循GNU的选择标准,但这些都不奏效。
是否有直接的解决方法?
编辑:
事实证明,这是阅读信息页而不是手册页的时间之一。
从信息页面:
`--force'
`-f'
Force compression or decompression even if the file has multiple
links or the corresponding file already exists, or if the
compressed data is read from or written to a terminal. If the
input data is not in a format recognized by `gzip', and if the
option `--stdout' is also given, copy the input data without
change to the standard output: let `zcat' behave as `cat'. If
`-f' is not given, and when not running in the background, `gzip'
prompts to verify whether an existing file should be overwritten.
Run Code Online (Sandbox Code Playgroud)
手册页缺少文本并且不在后台运行时
在后台运行时,gzip 不会提示,除非-f调用该选项,否则不会覆盖。
Bar*_*den 16
我能找到的最接近单个命令的内容如下:
yes n | gzip archive/foo
Run Code Online (Sandbox Code Playgroud)
该yes命令打印y后跟一个换行符到标准输出,直到它收到一个信号。如果它有参数,它将打印它而不是y. 在这种情况下,它会n一直打印直到 gzip 退出,从而关闭管道。
这相当于n在键盘上反复输入;这将自动回答问题gzip: archive/foo.gz already exists; do you wish to overwrite (y or n)?
我一般来说,如果有对应的gzip压缩文件,我认为最好不要尝试压缩文件;我的解决方案比较嘈杂,但它符合我的特殊需求,即直接替换gzip命令,位于配置文件中。
Яро*_*лин 11
我意识到避免不希望的效果的最好方法是不要让程序执行不希望的效果。也就是说,如果文件已经以压缩形式存在,就不要告诉它压缩文件。
例如:
if [ ! -f "$file.gz" ]; then
gzip "$file";
else
echo "skipping $file"
fi
Run Code Online (Sandbox Code Playgroud)
或更短(true如果有 file.gz 则运行,否则压缩文件)
[ -f "$file.gz" ] && echo "skipping $file" || gzip "$file"
Run Code Online (Sandbox Code Playgroud)