-4

I have written the following script

#!/bin/bash
echo "Power Details"
fall='/sys/class/power_supply/BAT1'
full=cat $fall/energy_full
echo 'printing here'
echo $full

It is showing the following error:

./power.sh: line 4: /sys/class/power_supply/BAT1/energy_full: Permission denied

The file I am accessing has read permissions to all. Also, while I am simply printing the output of the file, like (editing line 4 of the code):

cat $path/energy_full

It shows no error. Why is this so? How are cat filename v/s var1 = cat filename different? What should I do to resolve the issue, without changing read-write-execute permissions of the file I want to access?
NOTE: I am running Kali Linux as a root user

4
  • 2
  • This is probably because read privilege is different from execute privilege, and even the root user needs execute privilege to execute. To fix do: chmod a+x ./power.sh. Do man chmod for more information on how privileges work. Mar 21, 2017 at 22:25
  • Try enable the "BASIC debugger", which is: add set -x in line 2 of the script. This will echo the commands to the console while executing them.
    – hschou
    Mar 21, 2017 at 22:30
  • @John I thought of the same thing, regarding privileges. But the thing that confused me is how simple cat command is working while redirecting the output a variable not. What makes the two commands different?
    – Ugnes
    Mar 21, 2017 at 22:37

1 Answer 1

8

The problem is that you are using the wrong syntax to assign the output of a command to a variable.

To answer your question as asked, the difference between cat filename and var=cat filename is that in the first case you are executing the command cat on filename. In the second, you are executing the command filename while setting the value of var to cat. However, filename is not an executable command, so you are getting a permission error.

Since you actually want to assign the output of the cat command to a variable, you need to do it like this:

var=$(cat filename)
2
  • 1
    And quote those variables when you use them, full=$(cat "$fall/energy_full")
    – roaima
    Mar 21, 2017 at 22:48
  • 3
    BTW, the command var1 = cat filename (given in the discussion) would do something still different -- it would try to run var as a command, with the parameters "=", "cat", and "filename". In the shell spaces matter so x=y and x = y do totally different things. Also, expanding @roaima's comment, you should also use double-quotes when echoing the result (echo "$full", not echo $full). Mar 21, 2017 at 23:11

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.