2

I assume arguments to my shell scripts willbe ./x.sh subject N file1 file2 fileN So I am splicing argv from 3 till end candidates=${@:3}

now I want to check whether length of candidates is same as given N I am trying with echo $((${#candidates[@]})) which is always returning 1.

I can do echo "$#-2" | bc but, I shouldn't I be able to get array size ?

I can use bc to do integer comparison. but I've to know the size of `candidates array which I am not getting properly.

2
  • 1
    What shell? Many shells don't even support arrays! Commented Dec 14, 2012 at 16:48
  • Yes, but what shell? ${@:3} is a syntax error in many shells. Commented Dec 14, 2012 at 16:51

1 Answer 1

2

The way you are assigning candidates is not making an array. To make it an array, do:

candidates=(${@:3})

In bash, you can get the number of elements in the array with ${#candidates[*]}. To check if that is equal to $2, just do:

[[ ${#candidates[*]} == "$2" ]]
Sign up to request clarification or add additional context in comments.

6 Comments

candidates=${@:3} echo ${#candidates[*]} is returning 1
candidates is not an array!
Thanks the parenthesis fixed it. one more question here I am slicing 3 to end. but how can I slice 3 to end-1 th element ?
You could do: candidates=(${@:3:$(($#-3))})
candidates=(${@:3:n}) always gets first element only doesn't matter whatever I put in place of n
|

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.