There is a difference in the output of commands that I don't understand, as stated below:

echo "$INPUT ${#INPUT} ${#INPUT[@]} ${#@}"
# outputs: a b c 5 1 3

arr=(a b c)
echo "$arr ${#arr} ${#arr[@]}"
# outputs: a 1 3

I run a script with ./my_script.sh a b c.

I understand that echo "$arr" is dereferencing $arr to the first element, and then printing a. At the same time for the command $INPUT it prints a b c.

For the command ${#INPUT} and ${#INPUT[@]} why is the output 5 and 1 respectively. Shouldn't it be similar to output of the commands ${#arr} and ${#arr[@]}?


You assigned the array $@ to a scalar INPUT, which resulted in the string a b c, to which the length computation says 5 and the number of elements in the "array" is 1.

Perhaps you meant to assign the array as an array?

input=( "$@" )
  • 1
    ok, So the shell aggregates the positional parameters and two spaces to output 5. – HarshvardhanSharma Dec 7 '18 at 16:05
  • Does "$#" expand to a number or a string? – HarshvardhanSharma Dec 7 '18 at 16:47
  • 1
    What's the practical difference? It's a "string" of bytes that corresponds to a number. You can use it in numerical comparisons. – Jeff Schaller Dec 7 '18 at 16:48
  • I am trying to execute a programme with command ./my_script 1992. In the logic I do a if conditional if [[ "$#" -eq 0 || "$#" -gt 1 ]] then ` echo "Usage: error` else .... I always get only the error message, whereas echo "$#" outputs 1. – HarshvardhanSharma Dec 7 '18 at 16:54
  • the || operators aren't valid inside [[ -- move them outside, or simplify the test: if [[ "$#" -ne 1 ]]... – Jeff Schaller Dec 7 '18 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.