2

I have written a one-liner bash script(bright.sh) to manually adjust the display brightness.

sudo sh -c 'echo "$1" > /sys/class/backlight/intel_backlight/brightness'

Here I take the brightness value from the terminal and pass it as an argument to the echo command. But on running the script, I get an I/O error as follows:

sh: echo: I/O error

What do I do in order to pass the argument successfully from the terminal and control the brightness manually? An example usage might look like:

./bright.sh 230

3 Answers 3

3

The $1 in the sh -c script will expand to the first command line argument of that script, not to the first command line argument of the calling script (since the sh -c script is single quoted).

The correct solution is not to inject the value of $1 from the calling script into the sudo script (this would allow for various interesting code injection vulnerabilities), but to pass $1 from the outer script to the inner:

sudo sh -c 'printf "%s\n" "$1" > /sys/class/backlight/intel_backlight/brightness' sh "$1"

Alternatively, use sudo tee to write to the file as root:

printf '%s\n' "$1" | sudo tee /sys/class/backlight/intel_backlight/brightness >/dev/null

If the data printed to the file is always an integer, use %d as the printf format placeholder instead of %s.

0

I was able to fix that by putting $1 outside the single inverted comma. Not sure if this is the best approach.

The working script now looks like-

sudo sh -c 'echo '$1' > /sys/class/backlight/intel_backlight/brightness'

-1

Yes you see the problem (your answer https://unix.stackexchange.com/a/481424/4778), but you still must quote the $1 (just in case). And don't forget to specify the interpreter (#!…)

«solution removed, as it does not quote properly, and has a security bug. see @Kusalananda answer.»

We can concatenate strings by touching them together. Double quotes will expand $ expressions, but single will not. In this case you could have put it all in a double quote, as the rest of the text has no $s, so it makes no difference.

0

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.