Reputation: 5570
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?
Upvotes: 1
Views: 2996
Reputation: 785008
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.Upvotes: 3
Reputation: 530990
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)
)
Upvotes: 1
Reputation: 22821
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
Upvotes: 1