1

I'm trying to write a script that get the actual brightness and decrease the string number by 0.1. I've tried numerous syntax but since I'm very new to bash this doesn't work.

#!/bin/sh

actualBrightness=$(xrandr --verbose | grep -i brightness | cut -f2 -d ' ')

echo ${actualBrightness} # 0.5 for ex

if [[ $actualBrightness < 1 ]]
  then
  newBrightness=$(($actualBrightness-0.1))
  echo $newBrightness # must be 0.4
fi
4
  • 1
    Please add example input Commented Jul 31, 2017 at 19:40
  • 2
    Bash cannot do floating point arithmetic. You need to use awk or bc for example Commented Jul 31, 2017 at 19:42
  • 2
    This could easily break, as you're using #!/bin/sh and [[ ]], but [[ ]] is a bash feature. Commented Jul 31, 2017 at 19:46
  • 1
    BTW, [[ $actualBrightness < 1 ]] is doing a string comparison. Even for integers, you want to use actual integer math -- as a string, for instance, 20 is greater than 100, since comparison is character-by-character left-to-right. Commented Jul 31, 2017 at 20:04

2 Answers 2

0

Suppose you have:

$ echo "$b"
0.5

The 0.5 only has meaning to Bash as a string. You need to use bc or awk to interpret that as a floating point value change or change its value:

$ echo "$b-.1" | bc
.4

Bash does not do floating point math -- only integer math and string manipulation.

So to change the value of b you would do:

$ b=$(echo "$b-.1" | bc)
$ echo "$b"
.4

You can also use bc for testing:

$ echo "0.55 > 7" | bc
0
$ echo "55.2 > 7" | bc
1

1 is 'true' and then use that in your Bash [[ test ]] like so:

[[ $(echo "5 > 1" | bc) -eq 1 ]] # sets $? to 0 for true or 1 for false
                                 # BACKWARDS from bc's exit code

Or, single statement:

$ [[ $(echo "5 > 1" | bc) -eq "1" ]] && echo "true" || echo "false"
true
$ [[ $(echo ".5 > 1" | bc) -eq "1" ]] && echo "true" || echo "false"
false
Sign up to request clarification or add additional context in comments.

3 Comments

Works like a charm, thanks a lot !
Make sure you are actually using bash by having #!/bin/bash as the shebang -- NOT #!/bin/sh or the [[ test ]] won't work.
Yes I've made the modification, learn something, thanks again !
0

You can use awk to facilitate the floating-point arithmetic:

actualBrightness='0.5'
awk '{if ($1 < 1) { new=($1 - 0.1); printf new; }}' <<<"$actualBrightness"
# output: 0.4

Explanation:

Awk operates on fields separated by a field-separator, which defaults to whitespace; the above statement checks to see:

  1. Is the first field less than 1
  2. Yes? Then set the variable new to ($1 - 0.1) and print new to STDOUT
  3. No? Then do nothing.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.