Shell Script error: command not found

Shell Script error: command not found

这是我的代码,旨在批量区分 .in 和 .out 文件。 .in 和 .out 文件都在同一目录中并按名称排序。因此,需要测试的两个文件在目录中应该是相邻的。但是当我想用outFile=${arr[$(i++)]}获取.out文件时,却显示i++: command not found。我的脚本有什么错误?

#!/bin/sh

dir=$PATH
arr=($dir/*)

for((i=0;i<${#arr[@]};i++));do
        inFile=${arr[$i]}
        outFile=${arr[$(i++)]}
        if diff $inFile $outFile > /dev/null; then
                echo Same
        else
                echo $inFile
        fi
done

使用$(( i++ ))。那是两个(不是一个)括号。

  • $( ) 运行 shell 个命令。
  • $(( )) 计算算术表达式。

还有:

  • 你的脚本使用了bash个特征(数组),最好用#!/bin/bash以免混淆。

  • 我不确定您希望 dir=$PATH 做什么? $PATH 是一个特殊的环境变量,用于查找命令。如果我正确理解脚本的意图,这可能不是您想要的。

  • i++ 将在使用 后增加值 ;所以这里 inFileoutFile 实际上是一样的!您可能想使用 ++i(这将修改变量,然后 然后 使用它),或者只是 i + 1(这不会修改变量)。

括号中的内容已经在算术上下文中进行了计算,就像在 $(( ... )) 中一样。所以你可以这样做:

for (( i=0; i < ${#arr[@]}; ));do
    inFile=${arr[i++]}
    outFile=${arr[i++]}

参考文献:
https://www.gnu.org/software/bash/manual/bashref.html#Arrays

The subscript is treated as an arithmetic expression ...

https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic

Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax.