1

This is a bash script I can run it normally

#!/bin/bash
array=$(awk '{print $4}' /var/log/httpd/access_log | uniq -c | cut -d[ -f1)
sum=0 
sum1=0
arr=(${array[*]}) 
echo "After unquoted expansion: ${#arr[*]}"

for (( i=1; i<${#arr[@]}; i++ )); 
do 
sum=$( expr $sum - ${arr[$i]} ) 
sum1=$( expr $sum1 + $sum ) 
done 
echo 
echo "Sum of \$arr = ${sum1}" 
exit $sum

but When I change

sum=$( expr $sum - ${arr[$i]} )

by

sum=$( expr ${arr[$i+1]} - ${arr[$i]} )

or

j=$( expr $i + 1) sum=$( expr ${arr[$j]} - ${arr[$i]} )

it has error: expr: syntax error

4
  • 1
    Change the shebang to #!/bin/bash -x to see how the commands are executed and to see the arguments of the expr when it fails. When you see it, you might know the answer yourself. Otherwise, add it to your post. Commented Nov 17, 2013 at 15:44
  • 1
    The assignment of array is not an array assignment! Commented Nov 17, 2013 at 16:04
  • when I use #!/bin/bash -x , I saw where the problem is. Thanks @janos a lot. Commented Nov 17, 2013 at 16:20
  • Instead of using expr you can do sum=$(( ${arr[$i+1]} - ${arr[$i]} )) for arithmetic expansion. You could possibly also use let ... Commented Nov 17, 2013 at 17:10

1 Answer 1

2

Change the shebang to #!/bin/bash -x to see how the commands are executed and to see the arguments of the expr when it fails. When you see it, you might know the answer yourself. Otherwise, add it to your post.

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

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.