简体   繁体   中英

Shell Script error: command not found

Here is my code aiming to diff .in and .out file in batches. Both .in and .out files are in same directory and sorted by name. So, two files needed to test should be adjacent in directory. But when I want to use outFile=${arr[$(i++)]} to get the .out file, it shows i++: command not found . What's the error in my script?

#!/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

Use $(( i++ )) . That's two (not one) parenthesis.

  • $( ) runs shell commands.
  • $(( )) evaluates arithmetic expressions.

Also:

  • Your script uses bash features (arrays), it's best to use #!/bin/bash to avoid confusion.

  • I'm not sure what you expect dir=$PATH to do? $PATH is a special environment variable that is used for the lookup of commands. This is probably not what you want, if I understand the intent of the script correctly.

  • i++ will increment the value after being used; so here inFile and outFile are in fact the same! You probably want to use ++i (which will modify the variable and then use it), or just i + 1 (which will not modify the variable).

The stuff in brackets is already evaluated in arithmetic context, like within $(( ... )) . So you can do:

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

References:
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM