1

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
1
  • 1
    PATH is (nearly always) not a single directory, but a colon-separated list of directories. Commented Apr 1, 2016 at 14:26

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

1 Comment

i++ also means you're modifying i in two places; just use $(( i + 1)) for outFile, and use i+=2 in the for loop to iterate over two files at a time.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.