i would like to know how would you find how many variables are stored in a variable..for example:
dir=$(ls)
dir would store the names of all the files in the directory and i know you can cycle through them with a while-do loop. but is there a way for me to know how many variables (file names in this case) are stored in the variable (dir)?
thanks
A clean way would be to use bash arrays.
EDIT: The above does not handle spaces properly, see Glenn’s answer for the correct way, which still creates a bash array:
Notice the additional braces above. i.e. I declared dir to be an array, rather than a single variable.
Then you can simply get the number of elements in dir (the array):
You can access the individual elements:
More details here: http://tldp.org/LDP/abs/html/arrays.html