shell命令按顺序跳过文件

shell command to skip file in sequence

I 运行 几个数据文件的 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 命令以跳过丢失的输入文件并移至下一个输入文件?

谢谢。

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

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

顺便说一句,&& 表示法是 shorthand 表示 if。参见 help ifman sh

您可以使用 {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`