Bash nested command substitution not working

bashshell-script

Hi I have a bash script that intend to run via watch ./script.sh

It's to debug a cooling problem with my laptop, however the script I wrote isn't working as intended. I'm quite new to bash scripting so I'm sure its something simple.

I have a line in my script that has a nested command substitution but the inner command doesn't appear to work or at least it looks like the inner command doesn't know the value of $i. Any help appreciated.

here's the script:

echo "THERMAL ZONE 2:"
echo "Cur Temp: $(cat /sys/class/thermal/thermal_zone2/temp)"

for i in {2..7}
do
echo "cooling_device$i STATE: $(cat /sys/class/thermal/thermal_zone2/cdev$i/cur_state) TRIP POINT TEMP: $(cat /sys/class/thermal/thermal_zone2/trip_point_$(cat /sys/class/thermal/thermal_zone2/cdev$i_trip_point)_temp)"
done

and heres the output:

THERMAL ZONE 2:
Cur Temp: 43000
cat: /sys/class/thermal/thermal_zone2/cdev: No such file or directory
cat: /sys/class/thermal/thermal_zone2/trip_point__temp: No such file or directory
cooling_device2 STATE: 1 TRIP POINT TEMP: 
cat: /sys/class/thermal/thermal_zone2/cdev: No such file or directory
cat: /sys/class/thermal/thermal_zone2/trip_point__temp: No such file or directory
cooling_device3 STATE: 1 TRIP POINT TEMP: 
cat: /sys/class/thermal/thermal_zone2/cdev: No such file or directory
cat: /sys/class/thermal/thermal_zone2/trip_point__temp: No such file or directory
cooling_device4 STATE: 0 TRIP POINT TEMP: 
cat: /sys/class/thermal/thermal_zone2/cdev: No such file or directory
cat: /sys/class/thermal/thermal_zone2/trip_point__temp: No such file or directory
cooling_device5 STATE: 0 TRIP POINT TEMP: 
cat: /sys/class/thermal/thermal_zone2/cdev: No such file or directory
cat: /sys/class/thermal/thermal_zone2/trip_point__temp: No such file or directory
cooling_device6 STATE: 0 TRIP POINT TEMP: 
cat: /sys/class/thermal/thermal_zone2/cdev: No such file or directory
cat: /sys/class/thermal/thermal_zone2/trip_point__temp: No such file or directory
cooling_device7 STATE: 0 TRIP POINT TEMP:

Best Answer

The most obvious error I can see is that you're not protecting the i loop variable. So when you write $i_trip_point, the shell is looking for a variable named i_trip_point, which is not set so you get the second type of error, like this for example:

cat: /sys/class/thermal/thermal_zone2/trip_point__temp: No such file or directory

Two underscores between point and temp which marks an empty variable being interpolated. You should use the syntax ${i}_trip_point. The braces protect your variable from adjacent characters being interpreted as part of the variable name.

Related Question