1

I am trying to access some numeric values that a regular 'cat' outputs in an array.

If I do: cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies

I get: 51000 102000 204000 312000 ...

So I scripted as below to get all elements in an array and I tried to get the number of elements.

vAvailableFrequencies=$(sudo cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies)
nAvailableFrequencies=${#vAvailableFrequencies[@]}

The problem is that nAvailableFrequencies is equal to the number of characters in the array, not the number of elements.

The idea is to be able to access each element as:

for (( i=0;i<$nAvailableFrequencies;i++)); do
   element=${vAvailableFrequencies[$i]
done

Is this possible in bash without doing something like a sequential read and inserting elements in the array one by one?

3 Answers 3

3

You can use array like this:

arr=($(</sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies))

nAvailableFrequencies=${#arrr}
  • $(<file) reads and outputs a file content while (...) creates an array.
Sign up to request clarification or add additional context in comments.

Comments

1

You just need another set of brackets around the vAvailableFrequencies assignment:

vAvailableFrequencies=($(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies))
nAvailableFrequencies=${#vAvailableFrequencies[@]}

Now you can access within your for loop, or individually with ${vAvailableFrequencies[i]} where i is the number of an element

Comments

1

If you are using bash 4 or later, use

readfile -t vAvailableFrequencies < /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies

(or, if you need to use sudo,

readfile -t vAvailableFrequencies < <(sudo cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies)

)

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.