linux - tar 在脚本中返回 1,但不以交互方式返回

标签 linux bash ubuntu tar

如果我运行以下 shell 脚本 (即 tar 文件,如果成功则删除源)

#!/bin/bash
tar cvf /home/acampton/vortex_data/2014-02-14/tmp-2014-02-14-test2.tar -C /home/acampton/vortex_data/2014-02-14 SIC_17_RADAR-2014-02-14_all_no_dups.csv
if [ $? -ne 0 ]; then 
then
 echo "Deleting files - tar successful ($?) at time "`date`
else
 echo "Not Deleting files - tar unsuccessful ($?) at time "`date`
fi

它返回 1(= 源文件在归档时被更改)

acampton@ALIEN:~/work/spm$ ./v1.sh
SIC_17_RADAR-2014-02-14_all_no_dups.csv
Not Deleting files - tar unsuccessful (1) at time Tue Feb 18 10:38:16 EST 2014

但如果我以交互方式运行它,它就会起作用(每次!)

acampton@ALIEN:~/work/spm$ tar cvf /home/acampton/vortex_data/2014-02-14/tmp-2014-02-14-test2.tar -C /home/acampton/vortex_data/2014-02-14 SIC_17_RADAR-2014-02-14_all_no_dups.csv
SIC_17_RADAR-2014-02-14_all_no_dups.csv
acampton@ALIEN:~/work/spm$ echo $?
0
acampton@ALIEN:~/work/spm$

而且我可以保证当我运行脚本(或交互式)时源没有被修改

我也试过使用 --exclude=everything_else_but_my_file 得到同样的结果

请注意,我并不是要加油。 (这通常会给出“文件在我们读取时已更改”,因为它试图压缩自己的 .tar 文件)

我已无计可施 - 寻找 tar 的替代品,但需要知道为什么会这样,这样我才能在晚上安然休眠

有什么想法吗?

最佳答案

if 条件是倒退的。 0 表示成功,非零表示失败。使用 -eq 而不是 -ne。此外,您还有一个额外的 then

if [ $? -eq 0 ]; then 
 echo "Deleting files - tar successful ($?) at time "`date`
else
 echo "Not Deleting files - tar unsuccessful ($?) at time "`date`
fi

实际上,测试命令是否成功的惯用方法是将其放在 if 语句中。

if tar cvf /home/acampton/vortex_data/2014-02-14/tmp-2014-02-14-test2.tar -C /home/acampton/vortex_data/2014-02-14 SIC_17_RADAR-2014-02-14_all_no_dups.csv; then
 echo "Deleting files - tar successful ($?) at time $(date)"
else
 echo "Not Deleting files - tar unsuccessful ($?) at time $(date)"
fi

关于linux - tar 在脚本中返回 1,但不以交互方式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21842405/

相关文章:

linux - Libcamera 构建的 Meson 安装失败

linux - Unix 命令删除了每个目录,即使没有指定

bash - 如何退出 bash 中的所有调用脚本?

php - Laravel 无法在 ubuntu 15.04 中运行

c++ - Linux:为什么加载程序找到我的共享库?

linux - 如何修复/使用这个基本的 crontab?

ruby - rvm 没有设置 ruby​​ 版本

c# - Mono 编译器生成的 .exe 直接从 linux 命令行运行,为什么?

linux - 更改/etc/fstab 的位置

Linux 机器上存在 PHP file_exists 和特殊字符,如 Å Ø Æ