shell命令按顺序跳过文件

时间:2015-06-17 15:12:55

标签: shell sh

我使用以下命令按顺序运行多个数据文件的C ++代码:

for i in $(seq 0 100); do ./f.out c2.$(($i*40+495)).bin `c2.avg.$(($i*40+495)).txt; done`

现在如果缺少某些输入文件,比如缺少c2.575.bin,则不会对其余文件执行该命令。如何修改shell命令以跳过缺少的输入文件并移动到下一个输入文件?

感谢。

2 个答案:

答案 0 :(得分:2)

在循环中,在调用操作该文件的程序之前测试文件是否存在:

for i in $(seq 0 100); do
  INPUT=c2.$(($i*40+495)).bin
  test -e $INPUT && ./f.out $INPUT c2.avg.$(($i*40+495)).txt
done

这样,./f.out ...将仅对现有输入文件执行。

有关详细信息,请参阅man test

顺便说一下,&&符号是if的简写。请参阅help ifman sh

答案 1 :(得分:2)

您可以使用{0..100}代替$(seq 0 100)以提高可读性。您可以将以下代码放在脚本中并执行脚本。例如,runCode.bash

#!/bin/bash
for i in {0..100}
do
  # Assign a variable for the filenames
  ifn=c2.$(($i*40+495)).bin
  # -s option checks if the file exists and size greater than zero
  if [ -s "${ifn}" ]; then
     ./f.out "${ifn}" c2.avg.$(($i*40+495)).txt
  else
     echo "${ifn} No such file"
  fi
done

更改权限并执行脚本。

chmod u+x runCode.bash`
./runCode.bash`